티스토리 뷰

www.acmicpc.net/problem/11725

 

11725번: 트리의 부모 찾기

루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.

www.acmicpc.net

백준 소스코드 [C++] 11725 트리의 부모 찾기

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
#include <set>
#define all(v) v.begin(), v.end()
#define pii pair<int,int>
#define make_unique(v) v.erase(unique(v.begin(), v.end()), v.end())
typedef long long ll;
using namespace std;
vector<int> tree[100001];
int res[100001];
void dfs(int s) {


	for (int i = 0;i < tree[s].size();i++) {
		if (res[tree[s][i]] == 0) {
			res[tree[s][i]] = s;
			dfs(tree[s][i]);
		}
	}

}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, a, b;
	cin >> n;
	res[1] = 1;
	for (int i = 1;i < n;i++) {
		cin >> a >> b;
		tree[a].push_back(b);
		tree[b].push_back(a);
	}
	dfs(1);
	for (int i = 2;i <= n;i++) cout << res[i] << '\n';
	return 0;
}
댓글