11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <sstream>
using namespace std;
const int MAX = 100111;
vector<int> a[MAX];
int parent[MAX];
bool check[MAX];
int depth[MAX];
int dist[MAX];
int main() {
int n;
scanf("%d",&n);
for (int i=0; i<n-1; i++) {
int u,v,w;
scanf("%d %d",&u,&v);
a[u].push_back(v);
a[v].push_back(u);
}
depth[1] = 0;
check[1] = true;
queue<int> q;
q.push(1);
parent[1] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
for (int y : a[x]) {
if (!check[y]) {
depth[y] = depth[x] + 1;
check[y] = true;
parent[y] = x;
q.push(y);
}
}
}
for (int i=2; i<=n; i++) {
printf("%d\n",parent[i]);
}
return 0;
}
'Problem set' 카테고리의 다른 글
[백준] 1967 트리의 지름 (0) | 2021.02.20 |
---|---|
[백준] 1167 트리의 지름 (0) | 2021.02.20 |
[백준] 2250 트리의 높이와 너비 (0) | 2021.02.20 |
[백준] 1991 트리 순회 (0) | 2021.02.20 |
[백준] 1261 알고스팟 (0) | 2021.02.20 |