11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
그래프에 입력받고 DFS이던 BFS이던 해준 뒤에 2부터 N까지의 부모 노드를 저장해주면 된다.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<vector<int>> ar;
bool vis[100001];
map<int, int> M;
void dfs(int cur) {
vis[cur] = true;
for (auto i : ar[cur]) {
if (!vis[i]) {
M[i] = cur;
dfs(i);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
ar.resize(n + 1);
for (int i = 0; i < n - 1; i++) {
int x, y; cin >> x >> y;
ar[x].push_back(y);
ar[y].push_back(x);
}
dfs(1);
for (auto i : M) {
cout << i.second << '\n';
}
return 0;
}
map도 연습해볼 겸 사용해봤다.
'알고리즘 > BOJ' 카테고리의 다른 글
백준 1167 트리의 지름 (0) | 2020.09.10 |
---|---|
백준 1967 트리의 지름 (0) | 2020.09.10 |
백준 1991 트리 순회 (0) | 2020.09.10 |
백준 19699 소-난다! (0) | 2020.09.10 |
백준 2146 다리 만들기 (0) | 2020.09.10 |