백준 11725번 (트리의 부모 찾기, C++) [BAEKJOON]
문제
https://www.acmicpc.net/problem/11725
| 시간 제한 | 메모리 제한 | 제출 | 정답 | 맞힌 사람 | 정답 비율 |
|---|---|---|---|---|---|
| 1 초 | 256 MB | 60311 | 26553 | 18833 | 42.193% |
루트 없는 트리가 주어진다.
이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다.
둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.
출력
첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.
예제 입력 1
plaintext
7
1 6
6 3
3 5
4 1
2 4
4 7
예제 출력 1
plaintext
4
6
1
3
1
4
예제 입력 2
plaintext
12
1 2
1 3
2 4
3 5
3 6
4 7
4 8
5 9
5 10
6 11
6 12
예제 출력 2
plaintext
1
1
2
3
3
4
4
5
5
6
6
cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Node
{
int _Number;
int _Parent = -1;
vector<int> _Nodes;
Node(int p_Number)
{
_Number = p_Number;
}
};
queue<int> _MyQueue;
vector<Node> _NodesV;
int _N;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> _N;
for (int i = 0; i <= _N; i++) {
Node _NewNode(i);
_NodesV.push_back(_NewNode);
}
for (int i = 1; i < _N; i++) {
int _First, _Second;
cin >> _First >> _Second;
_NodesV[_First]._Nodes.push_back(_Second);
_NodesV[_Second]._Nodes.push_back(_First);
}
_MyQueue.push(1);
while (!_MyQueue.empty()) {
int CntNode = _MyQueue.front();
_MyQueue.pop();
for (auto& it : _NodesV[CntNode]._Nodes) {
if (_NodesV[it]._Parent != -1) continue;
_NodesV[it]._Parent = CntNode;
_MyQueue.push(it);
}
}
for (int i = 2; i <= _N; i++) {
cout << _NodesV[i]._Parent << "\n";
}
return 0;
}