https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다
www.acmicpc.net
노드를 어떻게 제거하는가?
루트 노드부터
dfs 탐색을 수행하면서
리프 노드(자식이 없는 노드)의
개수를 센다.
그리고 삭제 노드를 만나면
탐색을 종료!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#include <iostream>
#include <vector>
using namespace std;
vector<bool> visited;
vector<vector<int>> tree;
int ans = 0;
int sakujyo = 0;
void dfs(int num)
{
visited[num] = true;
int musuko = 0;
for (int now : tree[num])
{
if (!visited[now] && now != sakujyo)
{
musuko++;
dfs(now);
}
}
// 자식 노드 수가 0이면 리프 노드
if (musuko == 0)
ans++;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
int root = 0;
visited.resize(n + 1);
tree.resize(n + 1);
for (int i = 0; i < n; i++)
{
int p;
cin >> p;
if (p != -1)
{
tree[i].push_back(p);
tree[p].push_back(i);
}
else
root = i;
}
cin >> sakujyo;
if (sakujyo == root)
cout << 0 << '\n';
else
{
dfs(root);
cout << ans << '\n';
}
}
|
cs |