-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindTreesParent.cpp
More file actions
48 lines (40 loc) · 1.03 KB
/
findTreesParent.cpp
File metadata and controls
48 lines (40 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
using namespace std;
vector<int> graph[100001];
vector<bool> isChecked(100001 , false);
vector<int> result(100001);
queue< vector<int> > q;
int main() {
int n = 0, start , end;
cin >> n;
for(int i = 0; i < n - 1; i++) {
cin >> start >> end;
graph[start].push_back(end);
graph[end].push_back(start);
}
queue<int> index;
index.push(1);
q.push(graph[index.front()]);
while(!q.empty()){
vector<int> node = q.front();
q.pop();
int currentNodeIndex = index.front();
index.pop();
for( int i = 0, len = node.size(); i < len; i++ ) {
if(!isChecked[node[i]]) {
result[node[i]] = currentNodeIndex;
isChecked[node[i]] = true;
q.push(graph[node[i]]);
index.push(node[i]);
}
}
}
for (int i = 2; i <= n; i++ ) {
cout << result[i] << '\n';
}
return 0;
}