hdu5647

链接:hdu5647

Description

  • DZY has an unrooted tree consisting of n nodes labeled from 1 to n.

  • DZY likes connected sets on the tree. A connected set S is a set of nodes, such that every two nodes u,v in S

  • can be connected by a path on the tree, and the path should only contain nodes from
  • S. Obviously, a set consisting of a single node is also considered a connected set.

  • The size of a connected set is defined by the number of nodes which it contains. DZY wants to know the sum of

  • the sizes of all the connected sets. Can you help him count it?

  • The answer may be large. Please output modulo 109+7.

    Input

  • First line contains t denoting the number of testcases.t testcases follow. In each testcase, first line
  • contains n. In lines 2∼n, ith line contains pi, meaning there is an edge between node i and node pi.
  • (1≤pi≤i−1,2≤i≤n) (n≥1, sum of n in all testcases does not exceed 200000)

    Output

  • Output one line for each testcase, modulo 109+7.

    Sample Input

    2
    1
    5
    1
    2
    2
    3

    Sample Output

    1
    42

    题解

  • ans[i]由两部分组成,这个节点做的贡献dp[u](sum[x]+1) 孩子做的贡献dp[x]sum[u]
  • 具体看代码
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
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,x,y) for(register int i=x;i<=y;++i)
#define repd(i,x,y) for(register int i=x;i>=y;--i)
#define ll long long
using namespace std;
const int N=1e6;
const int mod=1e9+7;
int T,n;
ll dp[N],sum[N],head[N],cnt;
ll ans;
struct node{
int v,nxt;
}e[N];

void readin(){
scanf("%d",&n);
rep(i,2,n){
int x;
scanf("%d",&x);
e[cnt].v=i;
e[cnt].nxt=head[x];
head[x]=cnt++;
}
}

void dfs(int u){
sum[u]=1;
dp[u]=1;
for(int i=head[u];i!=-1;i=e[i].nxt){
int x=e[i].v;
dfs(x);
dp[u]=(dp[u]*(sum[x]+1)%mod+dp[x]*sum[u]%mod)%mod;//新加的点做的贡献+这个孩子原来做的贡献
sum[u]=(sum[u]*(sum[x]+1))%mod;
}
ans=(ans+dp[u])%mod;
}

int main(){
//ios::sync_with_stdio(false);
scanf("%d",&T);
while(T--){
ans=0;
cnt=0;
memset(head,-1,sizeof(head));
readin();
dfs(1);
//cout<<ans<<endl;
printf("%lld\n",ans);
}
return 0;
}