Algorithm
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.
Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.
The definition of a rooted tree can be found here.
The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i).
Vertex 1 is the root. It's guaranteed that the root has at least 2 children.
Print "Yes" if the tree is a spruce and "No" otherwise.
4
1
1
1
Yes
7
1
1
1
2
2
2
No
8
1
1
1
1
3
3
3
Yes
The first example:
The second example:
It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.
The third example:
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n;
vector<vector<int> > g;
int main() {
scanf("%d", &n);
g.resize(n);
for(int i = 1, tmp; i < n; ++i) {
scanf("%d", &tmp);
g[--tmp].push_back(i);
}
for(int i = 0, cnt; i < n; ++i) {
cnt = 0;
if(g[i].empty())
continue;
for(int j = 0; j < g[i].size(); ++j)
if(g[g[i][j]].empty())
++cnt;
if(cnt < 3) {
puts("No");
return 0;
}
}
puts("Yes");
return 0;
}
Copy The Code &
Try With Live Editor
Input
1
1
1
Output
Demonstration
Codeforces Solution-Christmas Spruce-Solution in C, C++, Java, Python