Algorithm
[백준/DFS] 11725 - 트리의 부모 찾기
strawberry_toast
2019. 9. 15. 23:25
문제
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.
출력
첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.
예제 입력 1
7 1 6 6 3 3 5 4 1 2 4 4 7
예제 출력 1
4 6 1 3 1 4
예제 입력 2
12 1 2 1 3 2 4 3 5 3 6 4 7 4 8 5 9 5 10 6 11 6 12
예제 출력 2
1 1 2 3 3 4 4 5 5 6 6
https://www.acmicpc.net/problem/11725
내 소스
#include <iostream>
#include <vector>
using namespace std;
struct tree{
int parent;
vector<int> children;
} tree[100001];
bool visited[100005];
void DFS(int k){
int curC;
long int cSize = tree[k].children.size();
for(int i=0; i<cSize; i++){
curC = tree[k].children[i];
if(visited[curC]){
tree[k].parent = curC;
}else{
visited[curC]=true;
DFS(curC);
}
}
}
int main(){
int n, i;
int tmp1, tmp2;
cin >> n;
for(i=1; i<n; i++){
cin >> tmp1;
cin >> tmp2;
tree[tmp1].children.push_back(tmp2);
tree[tmp2].children.push_back(tmp1);
}
visited[1] = true;
DFS(1);
for(i=2; i<=n; i++){
cout << tree[i].parent << "\n";
}
return 0;
}