# 4. 5G网络建设
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.on('close', () => {
class Edge {
constructor(u, v, cost, pre) {
this.u=u;
this.v=v;
this.cost = cost;
this.pre = pre;
}
}
function union(x, y) {
let rootX = find(X);
let rootY = find(Y);
if (rootX != rootY) {
parent[rootX] = rootY;
}
}
function find(x) {
if (parent[x] !== x) {
parent[x] = find(parent[x]);// 路径压缩
}
return parent[x];
}
let N = parseInt(lines[0]);
let M = parseInt(lines[1]);
let parent = Array.from({length: N+1}, (_, i) => i);
let edges = []; //存储所有边
for(let i=2; i<lines.length; i++) {
let [X,Y,Z,P] = lines[i].split(' ').map(Number);
edges.push(new Edge(X,Y,Z,P));
if(P === 1) {
union(X, Y);
}
}
edges.sort((a, b) => a.cost - b.cost);
let cost = 0;
for(let edge of edges) {
if (find(edge.u) !== find(edge.v)) {
cost += edge.cost;
union(edge.u, edge.v);
}
}
for(let i=2; i<=N; i++) {
if (find(i) !== find(1)) {
console.log(-1);
return;
}
}
console.log(cost);
})
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
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
← 3. 欢乐的周末 5. MELON的难题 →