Skip to content

Commit 8d5796c

Browse files
[BOJ] 17352 여러분의 다리가 되어드리겠습니다! (G5)
1 parent 63f7ecc commit 8d5796c

File tree

2 files changed

+52
-12
lines changed

2 files changed

+52
-12
lines changed

서정우/7주차/260211.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const fs = require("fs");
2+
const filePath =
3+
process.platform === "linux" ? "/dev/stdin" : "./서정우/input.txt";
4+
const input = fs
5+
.readFileSync(filePath)
6+
.toString()
7+
.trim()
8+
.split("\n")
9+
.map((el) => el.trim());
10+
const N = Number(input[0]);
11+
12+
class UnionFind {
13+
constructor(size) {
14+
this.parent = Array.from({ length: size }, (_, idx) => idx);
15+
}
16+
17+
find(x) {
18+
if (this.parent[x] === x) return this.parent[x];
19+
return (this.parent[x] = this.find(this.parent[x]));
20+
}
21+
22+
union(a, b) {
23+
const rootA = this.find(a);
24+
const rootB = this.find(b);
25+
if (rootA !== rootB) {
26+
this.parent[rootB] = rootA;
27+
}
28+
}
29+
}
30+
31+
const uf = new UnionFind(N);
32+
33+
for (let i = 1; i <= N - 2; i++) {
34+
const [a, b] = input[i].split(" ").map(Number);
35+
36+
uf.union(a - 1, b - 1);
37+
}
38+
39+
for (let i = 0; i < N; i++) {
40+
uf.parent[i] = uf.find(i);
41+
}
42+
43+
const parentsSet = new Set(uf.parent);
44+
45+
console.log(
46+
uf.parent.indexOf([...parentsSet][0]) + 1,
47+
uf.parent.indexOf([...parentsSet][1]) + 1,
48+
);

서정우/input.txt

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,4 @@
1-
11
2-
5 10
3-
6 25
4-
10 21
5-
32 43
6-
100 100
7-
50 50
8-
25 25
9-
45 67
10-
109 32
11-
128 128
12-
1 1
1+
5
2+
1 2
3+
2 3
4+
4 5

0 commit comments

Comments
 (0)