File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ const local_input = `
2
+ 7
3
+ 1 6
4
+ 6 3
5
+ 3 5
6
+ 4 1
7
+ 2 4
8
+ 4 7
9
+ ` ;
10
+
11
+ const input = process . execArgv . includes ( "--stack-size=65536" )
12
+ ? require ( "fs" ) . readFileSync ( "dev/stdin" ) . toString ( )
13
+ : local_input ;
14
+
15
+ const lines = input . trim ( ) . split ( '\n' ) ;
16
+
17
+ const N = Number ( lines [ 0 ] ) ;
18
+ const edges = lines . slice ( 1 ) . map ( el => el . split ( ' ' ) . map ( Number ) ) ;
19
+
20
+ const graph = { } ;
21
+
22
+ edges . forEach ( el => {
23
+ if ( ! graph [ el [ 0 ] ] ) graph [ el [ 0 ] ] = [ ] ;
24
+ if ( ! graph [ el [ 1 ] ] ) graph [ el [ 1 ] ] = [ ] ;
25
+ graph [ el [ 0 ] ] . push ( el [ 1 ] )
26
+ graph [ el [ 1 ] ] . push ( el [ 0 ] )
27
+ } )
28
+
29
+ const queue = [ 1 ] ;
30
+ const visited = new Set ( [ 1 ] ) ;
31
+ const parentNodes = [ ] ;
32
+
33
+ while ( queue . length ) {
34
+ const currentNode = queue . shift ( ) ;
35
+ const childNodes = graph [ currentNode ] . filter ( childNode => ! visited . has ( childNode ) ) ;
36
+
37
+ childNodes . forEach ( childNode => {
38
+ parentNodes [ childNode ] = currentNode ;
39
+ queue . push ( childNode ) ;
40
+ } )
41
+
42
+ visited . add ( currentNode ) ;
43
+ }
44
+
45
+ console . log ( parentNodes . slice ( 2 ) . join ( '\n' ) )
You can’t perform that action at this time.
0 commit comments