CF 461B Appleman and Tree 树形DP

时间:2022-02-08 19:57:03

Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.

Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.

Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).

Input

The first line contains an integer n (2  ≤ n ≤ 105) — the number of tree vertices.

The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1.

The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.

Output

Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7).

Sample test(s)
input
3
0 0
0 1 1
output
2
input
6
0 1 1 0 4
1 1 0 0 1 0
output
1
input
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1
output
27

题意:
一棵树,n个节点,编号为0~n-1
每一个节点涂有黑色或者白色,1代表黑色,0代表白色
若在树上去掉k条边,就把树分成k+1部分,每一个部分也是一棵树,若每一部分都有且只有一个节点是黑色,
则这是一个合理的操作。
求合理操作的方案数%(1e9+7) 如果把黑色看成节点的值为1,白色看成节点的值为0
一棵树的值=树上所有节点的值之和
则这道题转化为:
把一棵树分成若干个部分,每一部分的值都为1的方案数。 树形DP dp[i][0] : 以i为根的子树,i所在部分的值为0的方案数%mod
dp[i][1] : 以i为根的子树,i所在部分的值为1的方案数%mod 以root=0进行DFS
则输出:dp[0][1] 代码:
 #include<cstdio>
#include<cstring> using namespace std; const int maxn=1e5+;
const int mod=1e9+;
#define ll long long struct Edge
{
int to,next;
};
Edge edge[maxn<<];
int head[maxn];
int tot=;
ll dp[maxn][];
int cost[maxn]; void init()
{
memset(head,-,sizeof head);
memset(dp,,sizeof dp);
} void addedge(int u,int v)
{
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
} void solve(int );
void dfs(int ,int ); int main()
{
init();
int n;
scanf("%d",&n);
for(int i=;i<n;i++)
{
int p;
scanf("%d",&p);
addedge(i,p);
addedge(p,i);
}
for(int i=;i<n;i++)
{
scanf("%d",&cost[i]);
}
solve(n);
return ;
} void solve(int n)
{
dfs(,-);
printf("%d\n",(int)dp[][]);
return ;
} void dfs(int u,int pre)
{
if(cost[u])
{
dp[u][]=;
dp[u][]=;
}
else
{
dp[u][]=;
dp[u][]=;
}
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to;
if(v==pre)
continue;
dfs(v,u);
if(cost[u])
{
dp[u][]*=(dp[v][]+dp[v][]);
dp[u][]%=mod;
}
else
{
dp[u][]=dp[u][]*(dp[v][]+dp[v][])+dp[u][]*dp[v][];
dp[u][]%=mod;
dp[u][]*=(dp[v][]+dp[v][]);
dp[u][]%=mod;
}
}
}