Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9e66f22

Browse files
committed
feat: 53. 寻宝新增kruskal js解法
1 parent faeda4b commit 9e66f22

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎problems/kamacoder/0053.寻宝-Kruskal.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,62 @@ if __name__ == "__main__":
549549

550550
### Javascript
551551

552+
```js
553+
function kruskal(v, edges) {
554+
const father = Array.from({ length: v + 1 }, (_, i) => i)
555+
556+
function find(u){
557+
if (u === father[u]) {
558+
return u
559+
} else {
560+
father[u] = find(father[u])
561+
return father[u]
562+
}
563+
564+
}
565+
566+
function isSame(u, v) {
567+
let s = find(u)
568+
let t = find(v)
569+
return s === t
570+
}
571+
572+
function join(u, v) {
573+
let s = find(u)
574+
let t = find(v)
575+
if (s !== t) {
576+
father[s] = t
577+
}
578+
}
579+
580+
edges.sort((a, b) => a[2] - b[2])
581+
let result = 0
582+
for (const [v1, v2, w] of edges) {
583+
if (!isSame(v1, v2)) {
584+
result += w
585+
join(v1 ,v2)
586+
}
587+
}
588+
console.log(result)
589+
}
590+
591+
592+
async function main() {
593+
const rl = require('readline').createInterface({ input: process.stdin })
594+
const iter = rl[Symbol.asyncIterator]()
595+
const readline = async () => (await iter.next()).value
596+
const [v, e] = (await readline()).split(" ").map(Number)
597+
const edges = []
598+
for (let i = 0 ; i < e ; i++) {
599+
edges.push((await readline()).split(" ").map(Number))
600+
}
601+
kruskal(v, edges)
602+
}
603+
604+
605+
main()
606+
```
607+
552608
### TypeScript
553609

554610
### PhP

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /