第五届蓝桥杯校内选拔第七题_(树型dp)


G将军有一支训练有素的军队,这个军队除开G将军外,每名士兵都有一个直接上级(可能是其他士兵,也可能是G将军)。现在G将军将接受一个特别的任务,需要派遣一部分士兵(至少一个)组成一个敢死队,为了增加敢死队队员的独立性,要求如果一名士兵在敢死队中,他的直接上级不能在敢死队中。
请问,G将军有多少种派出敢死队的方法。注意,G将军也可以作为一个士兵进入敢死队。
输入格式
输入的第一行包含一个整数n,表示包括G将军在内的军队的人数。军队的士兵从1至n编号,G将军编号为1。
接下来n-1个数,分别表示编号为2, 3, ..., n的士兵的直接上级编号,编号i的士兵的直接上级的编号小于i。
输出格式
输出一个整数,表示派出敢死队的方案数。由于数目可能很大,你只需要输出这个数除10007的余数即可。
样例输入1
3
1 1
样例输出1
4
样例说明
这四种方式分别是:
1. 选1;
2. 选2;
3. 选3;
4. 选2, 3。
样例输入2
7
1 1 2 2 3 3
样例输出2
40

数据规模与约定
对于20%的数据,n ≤ 20;
对于40%的数据,n ≤ 100;
对于100%的数据,1 ≤ n ≤ 100000。


资源约定:
峰值内存消耗 < 256M
CPU消耗 < 2000ms

一道基础树型dp。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stdlib.h>
#include<algorithm>
#include<cmath>
using namespace std;
#define LL long long
#define N 100005
struct Eage
{
    int son,next;
} eage[4*N];
int head[N];
int cnte;
void addEage(int f,int s)
{
    eage[cnte].son=s;
    eage[cnte].next=head[f];
    head[f]=cnte++;
}

LL has[N],nhas[N];

void dfs(int now)
{
    if(head[now]==0)
    {
        has[now]=1;
        nhas[now]=0;
        return;
    }
    //int tmp1=0,tmp2=0;
    for(int i=head[now]; i!=0; i=eage[i].next)
    {
        int v=eage[i].son;
        dfs(v);
        has[now]=(has[now]+(has[now]*nhas[v])%10007)%10007;  //now去的情况,注意用到乘法
        has[now]=(has[now]+nhas[v])%10007;
        nhas[now]=(nhas[now]+(nhas[now]*(has[v]+nhas[v])%10007)%10007)%10007;  //now不去的情况
        nhas[now]=(nhas[now]+(has[v]+nhas[v])%10007);
    }
    has[now]++;
}

int main()
{
    int n;
    cnte=1;
    scanf("%d",&n);
    for(int i=2; i<=n; i++)
    {
        int f;
        scanf("%d",&f);
        addEage(f,i);
    }
    dfs(1);
    cout<<has[1]+nhas[1]<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/jasonlixuetao/p/6497656.html