File tree Expand file tree Collapse file tree 2 files changed +52
-12
lines changed
Expand file tree Collapse file tree 2 files changed +52
-12
lines changed Original file line number Diff line number Diff line change 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+ ) ;
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments