코딩테스트/백준

[실2] 11725 - 트리의 부모 찾기

ShovelingLife 2022. 10. 7. 14:22
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>

using namespace std;

#define MAX_SIZE 100001
vector<int> graph[MAX_SIZE];
int arr[MAX_SIZE];
bool vis[MAX_SIZE];

int main()
{
    int n; cin >> n;

    for (int i = 1; i < n; i++)
    {
        int y, x; cin >> y >> x;
        graph[y].push_back(x);
        graph[x].push_back(y);
    }
    stack<int> s; s.push(1);
    vis[1] = true;

    while (!s.empty())
    {
        auto idx = s.top(); s.pop();

        for (int i = 0; i < graph[idx].size(); i++)
        {
            auto next = graph[idx][i];

        	if (!vis[next])
            {
                vis[next] = true;
                arr[next] = idx;
                s.push(next);
            }
        }
    }
    for (int i = 2; i <= n; i++) 
        cout << arr[i] << "\n";
}