File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .io .*;
2+ import java .util .*;
3+
4+ public class Main {
5+
6+ public static List <List <Integer >> graph ;
7+ public static int [] visited ;
8+
9+ public static void main (String [] args ) throws IOException {
10+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
11+ int N = Integer .parseInt (br .readLine ());
12+ graph = new ArrayList <>();
13+ visited = new int [N +1 ];
14+ for (int i =0 ; i <=N ; i ++) {
15+ graph .add (new ArrayList <>());
16+ }
17+ for (int i =0 ; i <N -1 ; i ++) {
18+ StringTokenizer st = new StringTokenizer (br .readLine ());
19+ int v1 = Integer .parseInt (st .nextToken ());
20+ int v2 = Integer .parseInt (st .nextToken ());
21+ graph .get (v1 ).add (v2 );
22+ graph .get (v2 ).add (v1 );
23+ }
24+
25+ dfs (1 );
26+
27+ StringBuffer sb = new StringBuffer ();
28+ for (int i =2 ; i <=N ; i ++) {
29+ sb .append (visited [i ]).append ('\n' );
30+ }
31+ System .out .print (sb );
32+ }
33+
34+ public static void dfs (int n ) {
35+ List <Integer > list = graph .get (n );
36+ for (int i =0 ; i <list .size (); i ++) {
37+ int v = list .get (i );
38+ if (visited [v ] == 0 ) {
39+ visited [v ] = n ;
40+ dfs (v );
41+ }
42+ }
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments