6 Oct 2020

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

트리 부모 찾기

백준 11725


  • 정점들을 이어주는 그래프를 만든다.

  • root를 시작점으로 하여 bfs를 사용해 자식의 부모 노드를 찾는다.


#include <iostream>
#include <vector>
#include <algorithm>

const int MAX = 100001;
int n,from,to;
vector<int> tree[MAX];
int parent[MAX];
bool visited[MAX];

void bfs(){
    //root가 1번부터 시작
    queue<int> q;
    q.push(1);
    parent[1] = 1;
    while (!q.empty()) {
    	int now = q.front(); q.pop();
    	for (int i = 0; i < tree[now].size(); i++) {
    	    int next = tree[now][i];
    	    if (!visited[next]) {
    	    	visited[next] = true;
    	    	parent[next] = now;//부모 설정
    	    	q.push(next);
    	    }
    	}
    }
    for (int i = 2; i <= n; i++) {
    	cout << parent[i] << '\n';
    }
}
void input() {
    cin >> n;
    for (size_t i = 0; i < n-1; i++)
    {
	    cin >> from >> to;  
                //정점들을 이어준다.
    	tree[from].push_back(to);
    	tree[to].push_back(from);
    }
    bfs();
}

void solution() {
    input();
}

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

    solution();
    return 0;
}

Tags:
0 comments