-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path107-minimal-network.js
More file actions
73 lines (62 loc) · 1.42 KB
/
107-minimal-network.js
File metadata and controls
73 lines (62 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Minimal Network
* Time Complexity: O(M \log M)$
* Space Complexity: O(N + M)$
*/
function processData(input) {
const lines = input.trim().split(/\s+/);
let ptr = 0;
const N = parseInt(lines[ptr++], 10);
const M = parseInt(lines[ptr++], 10);
const edges = [];
for (let i = 0; i < M; i++) {
const u = parseInt(lines[ptr++], 10);
const v = parseInt(lines[ptr++], 10);
const w = parseInt(lines[ptr++], 10);
edges.push({ u, v, w });
}
edges.sort((a, b) => a.w - b.w);
const parent = new Int32Array(N + 1);
for (let i = 1; i <= N; i++) parent[i] = i;
function find(i) {
let root = i;
while (root !== parent[root]) {
root = parent[root];
}
let curr = i;
while (curr !== root) {
let next = parent[curr];
parent[curr] = root;
curr = next;
}
return root;
}
function union(i, j) {
const rootI = find(i);
const rootJ = find(j);
if (rootI !== rootJ) {
parent[rootI] = rootJ;
return true;
}
return false;
}
let mstWeight = 0;
let edgesCount = 0;
for (let i = 0; i < M; i++) {
const e = edges[i];
if (union(e.u, e.v)) {
mstWeight += e.w;
edgesCount++;
}
}
console.log(mstWeight);
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});