Codeforces Round #263 (Div.1) B. Appleman and Tree,
Address: http://codeforces.com/contest/461/problem/ B
For a tree, each vertex is white or black, and some edges are cut off so that each connected block has only one black spot.
Algorithm discussion: TreeDP. F [x] [0 .. 1] indicates that the connected block of x has 0/1 black spots. Set y to the son of x, then the DP equation is f [x] [1] = f [x] [1] * f [y] [0] + f [x] [1] * f [y]. [1] + f [x] [0] * f [y] [1], f [x] [0] = f [x] [0] * f [y] [0] + f [x] [0] * f [y] [1].
Code:
#include <cstdio>#define N 100000#define mod 1000000007using namespace std;long long f[N+10][2];int n,x,mm,next[N+10],son[N+10],ed[N+10],c[N+10];inline void add(int x,int y){next[++mm]=son[x],son[x]=mm,ed[mm]=y;}void dfs(int x){f[x][c[x]]=1;for (int i=son[x];i;i=next[i]){int y=ed[i];dfs(y);f[x][1]=(f[x][1]*f[y][0]%mod+f[x][1]*f[y][1]%mod+f[x][0]*f[y][1]%mod)%mod;f[x][0]=(f[x][0]*f[y][0]%mod+f[x][0]*f[y][1]%mod)%mod;}}int main(){scanf("%d",&n);for (int i=2;i<=n;++i) scanf("%d",&x),add(++x,i);for (int i=1;i<=n;++i) scanf("%d",&c[i]);dfs(1);printf("%I64d\n",f[1][1]);return 0;}
By Charlie Pan
Aug 27,2014