Codeforces 461B. Appleman and Tree[树形DP 方案数]
Posted Candy?
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 461B. Appleman and Tree[树形DP 方案数]相关的知识,希望对你有一定的参考价值。
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).
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 a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7).
3
0 0
0 1 1
2
6
0 1 1 0 4
1 1 0 0 1 0
1
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1
27
题意:分成若干个连通块,每个只有一个黑色节点,求方案数
f[i][0/1]表示以i为根的子树i是否在有黑色节点的连通块中的方案数
f[u][1]=(f[u][1]*(f[v][0]+f[v][1])+f[u][0]*f[v][1])%MOD; v是0 u跟他相连,v是1 不相连;u是0时要跟v是1相连
f[u][0]=f[u][0]*(f[v][0]+f[v][1])%MOD;同理
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; typedef long long ll; const int N=1e5+5,MOD=1e9+7; inline int read(){ char c=getchar();int x=0,f=1; while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1; c=getchar();} while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘; c=getchar();} return x*f; } struct edge{ int v,ne; }e[N<<1]; int cnt=0,h[N],w[N]; inline void ins(int u,int v){ cnt++; e[cnt].v=v;e[cnt].ne=h[u];h[u]=cnt; cnt++; e[cnt].v=u;e[cnt].ne=h[v];h[v]=cnt; } int n;ll f[N][2]; void dp(int u,int fa){ if(w[u]) f[u][1]=1; else f[u][0]=1; for(int i=h[u];i;i=e[i].ne){ int v=e[i].v; if(v==fa) continue; dp(v,u); f[u][1]=(f[u][1]*(f[v][0]+f[v][1])+f[u][0]*f[v][1])%MOD; f[u][0]=f[u][0]*(f[v][0]+f[v][1])%MOD; } } int main(){ n=read(); for(int i=1;i<=n-1;i++) ins(read(),i); for(int i=0;i<n;i++) w[i]=read(); dp(0,-1); cout<<f[0][1]; }
以上是关于Codeforces 461B. Appleman and Tree[树形DP 方案数]的主要内容,如果未能解决你的问题,请参考以下文章
CodeForces 461B Appleman and Tree:Tree dp
Codeforces461A Appleman and Toastman 贪心
Codeforces Round #263 (Div.1) B. Appleman and Tree
codeforces 416B. Appleman and Tree 树形dp