[백준] 11725 트리의 부모 찾기

0

백준

목록 보기
183/271
post-thumbnail
post-custom-banner

[백준] 11725 트리의 부모 찾기

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int n;
vector<vector<int>> adj(100000, vector<int>());

vector<bool> visited;

vector<int> parent;

void dfs(int cur) {
	if (visited[cur]) return;
	visited[cur] = true;

	for (int i = 0; i < adj[cur].size(); ++i) {
		int next = adj[cur][i];
		if (!visited[next]) {
			parent[next] = cur;
			dfs(next);
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	cin >> n;
	for (int i = 0; i < n-1; ++i) {
		int u, v;
		cin >> u >> v;
		adj[u - 1].push_back(v - 1);
		adj[v - 1].push_back(u - 1);
	}

	for (int i = 0; i < n; ++i) {
		visited.push_back(false);
		parent.push_back(-1);
	}
	dfs(0);

	for (int i = 1; i < n; ++i) {
		cout << parent[i] + 1 << "\n";
	}
	return 0;
}
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글