File tree 2 files changed +40
-0
lines changed
2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+
4
+ using namespace std ;
5
+ const int MAX = 100000 + 1 ;
6
+ int N;
7
+ bool visited[MAX];
8
+ int parent[MAX];
9
+ vector<int > tree[MAX];
10
+ void findParent (int nodeNum)
11
+ {
12
+ visited[nodeNum] = true ; // 방문한 노드 표시
13
+ // DFS
14
+ for (int i = 0 ; i<tree[nodeNum].size (); i++)
15
+ {
16
+ int next = tree[nodeNum][i];
17
+ if (!visited[next])
18
+ {
19
+ parent[next] = nodeNum; // next의 parent는 nodeNum
20
+ findParent (next);
21
+ }
22
+ }
23
+ }
24
+ int main (void )
25
+ {
26
+ ios_base::sync_with_stdio (0 );
27
+ cin.tie (0 );
28
+ cin >> N;
29
+ for (int i = 0 ; i < N - 1 ; i++)
30
+ {
31
+ int node1, node2;
32
+ cin >> node1 >> node2;
33
+ tree[node1].push_back (node2);
34
+ tree[node2].push_back (node1);
35
+ }
36
+ findParent (1 ); // root부터
37
+ for (int i = 2 ; i <= N; i++)
38
+ cout << parent[i] << " \n " ;
39
+ return 0 ;
40
+ }
You can’t perform that action at this time.
0 commit comments