mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2755 from suinming/kamacoder-53-kruskal-js
feat: 53. 寻宝新增kruskal js解法
This commit is contained in:
@ -549,6 +549,62 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
### Javascript
|
### Javascript
|
||||||
|
|
||||||
|
```js
|
||||||
|
function kruskal(v, edges) {
|
||||||
|
const father = Array.from({ length: v + 1 }, (_, i) => i)
|
||||||
|
|
||||||
|
function find(u){
|
||||||
|
if (u === father[u]) {
|
||||||
|
return u
|
||||||
|
} else {
|
||||||
|
father[u] = find(father[u])
|
||||||
|
return father[u]
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSame(u, v) {
|
||||||
|
let s = find(u)
|
||||||
|
let t = find(v)
|
||||||
|
return s === t
|
||||||
|
}
|
||||||
|
|
||||||
|
function join(u, v) {
|
||||||
|
let s = find(u)
|
||||||
|
let t = find(v)
|
||||||
|
if (s !== t) {
|
||||||
|
father[s] = t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
edges.sort((a, b) => a[2] - b[2])
|
||||||
|
let result = 0
|
||||||
|
for (const [v1, v2, w] of edges) {
|
||||||
|
if (!isSame(v1, v2)) {
|
||||||
|
result += w
|
||||||
|
join(v1 ,v2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const rl = require('readline').createInterface({ input: process.stdin })
|
||||||
|
const iter = rl[Symbol.asyncIterator]()
|
||||||
|
const readline = async () => (await iter.next()).value
|
||||||
|
const [v, e] = (await readline()).split(" ").map(Number)
|
||||||
|
const edges = []
|
||||||
|
for (let i = 0 ; i < e ; i++) {
|
||||||
|
edges.push((await readline()).split(" ").map(Number))
|
||||||
|
}
|
||||||
|
kruskal(v, edges)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
### TypeScript
|
### TypeScript
|
||||||
|
|
||||||
### PhP
|
### PhP
|
||||||
|
Reference in New Issue
Block a user