Codeforces Round #468 (Div. 2 )D. Peculiar apple-tree_BFS

题目简单,不多解释。
Code:

#include<cstdio>
#include<queue>
using namespace std;
const int maxn = 1000000 + 3;
int head[maxn], to[maxn], nex[maxn], cnt, dep[maxn], numv[maxn];
queue<int>Q;
inline void add_edge(int u,int v)
{
    nex[++cnt] = head[u], head[u] = cnt, to[cnt] = v;
}
int main()
{
    //freopen("input.in","r",stdin);
    int n;
    scanf("%d",&n);
    for(int i = 2;i <= n; ++i)
    {
        int a; scanf("%d",&a);
        add_edge(a,i);
    }
    Q.push(1); dep[1] = 1; numv[1] = 1;
    while(!Q.empty())
    {
        int u  = Q.front(); Q.pop();
        for(int v = head[u]; v ; v = nex[v])
        {
            dep[to[v]] = dep[u] + 1;
            ++numv[dep[to[v]]];
            Q.push(to[v]);
        }
    }
    int ans = 0;
    for(int i = 1;i <= 1000000; ++i) 
    {
        if(numv[i] % 2 == 1) ++ans;
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liyong1009s/article/details/82926243