题目链接:https://codeforces.com/problemset/problem/461/B
题目大意:
给你一个树,上面有黑点有白点,现在你可以删除k条边,0<=k<n,问你有多少种方案能够使得所有删除边后的连通块中只有一个黑点。
思路:
比较经典的树型dp,dp(u,0)表示以u为根节点的连通块,没有黑点的方案数,dp(u,1)表示以u为根节点的连通块,有一个黑点的方案数,那么有一下几种转移情况
-
首先如果儿子节点是个有黑点的,父亲节点也有黑点,那么只能分裂开,不能合并在一起
-
如果儿子节点是个有黑点的,父亲节点没有黑点,那么可以分裂也可以合并
-
如果儿子节点是个没有黑点的,父亲节点有黑点,那么必须和父亲合并
-
如果儿子节点是个没有黑点的,父亲节点也没黑点,那么必须和父亲合并
具体看代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <map>
#define int long long
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int maxn=1e5+10;
vector<int>G[maxn];
void init(int n){
for(int i=0;i<=n;i++){
G[i].clear();
}
}
int n;
int vis[maxn];
/*
dp[u][0]表示u的连通块中没有黑点的方案数
dp[u][1]表示u的连通块中有黑点的方案数
*/
ll dp[maxn][3];
int col[maxn];
void dfs(int u){
vis[u]=1;
dp[u][col[u]]=1;
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
if(vis[v])continue;
dfs(v);
ll temp0=dp[u][0],temp1=dp[u][1];
//当前连通块没有,要么子树没有,要么子树有,将子节点v和u断掉
dp[u][0]=temp0*((dp[v][0]+dp[v][1])%mod)%mod;
//当前连通块有,要么本来就有,子树没有或断掉子树,要么本来就没有,子树有
dp[u][1]=temp1*((dp[v][0]+dp[v][1])%mod)%mod+temp0*(dp[v][1])%mod;
dp[u][1]%=mod;
}
}
signed main(){
while(scanf("%d",&n)!=EOF){
init(n);
for(int i=1;i<n;i++){
int u;
scanf("%d",&u);
G[i].push_back(u);
G[u].push_back(i);
}
memset(vis,0,sizeof(vis));
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++){
scanf("%d",&col[i]);
}
dfs(0);
printf("%lld\n",dp[0][1]);
}
return 0;
}