Skip to content

Commit 0ff0d62

Browse files
[BOJ] 34548 와우 네트워크 (G4)
1 parent 5fd55fc commit 0ff0d62

File tree

2 files changed

+73
-6
lines changed

2 files changed

+73
-6
lines changed

서정우/5주차/260128.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
const fs = require("fs");
2+
const filePath = process.platform === "linux" ? "/dev/stdin" : "./서정우/input.txt";
3+
const input = fs.readFileSync(filePath).toString().trim().split("\n");
4+
5+
const [boothes, routersCount, MAX_TIME] = input[0].split(" ").map(Number);
6+
const routers = input.slice(1).map((line) => line.split(" ").map(Number));
7+
8+
const times = new Set();
9+
for (let i = 0; i < routers.length; i++) {
10+
times.add(routers[i][2]);
11+
}
12+
13+
const timesArray = Array.from(times).sort((a, b) => a - b);
14+
15+
class UnionFind {
16+
constructor(n) {
17+
this.parent = Array(n + 1)
18+
.fill(0)
19+
.map((_, i) => i);
20+
this.components = n; // 처음엔 모두 독립된 집합
21+
}
22+
23+
find(x) {
24+
if (this.parent[x] !== x) {
25+
this.parent[x] = this.find(this.parent[x]);
26+
}
27+
return this.parent[x];
28+
}
29+
30+
union(x, y) {
31+
const rootX = this.find(x);
32+
const rootY = this.find(y);
33+
34+
if (rootX !== rootY) {
35+
this.parent[rootX] = rootY;
36+
this.components--;
37+
return true;
38+
}
39+
return false;
40+
}
41+
42+
getComponents() {
43+
return this.components;
44+
}
45+
}
46+
47+
routers.sort((a, b) => a[2] - b[2]);
48+
49+
const uf = new UnionFind(boothes);
50+
let result = 0;
51+
let currentTime = 1;
52+
let routerIndex = 0;
53+
54+
for (const time of timesArray) {
55+
result += uf.getComponents() * (time - currentTime);
56+
57+
while (routerIndex < routers.length && routers[routerIndex][2] === time) {
58+
const [u, v, s] = routers[routerIndex];
59+
uf.union(u, v);
60+
routerIndex++;
61+
}
62+
63+
currentTime = time;
64+
}
65+
66+
result += uf.getComponents() * (MAX_TIME - currentTime + 1);
67+
68+
console.log(result);

서정우/input.txt

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
5
2-
0 1
3-
1 2
4-
3 1
5-
4 2
6-
5 1
1+
5 4 20
2+
1 2 3
3+
3 4 8
4+
2 3 12
5+
4 5 12

0 commit comments

Comments
 (0)