CF461B Appleman and Tree

感觉这题的dp挺神奇的,不是特别显然…
所以也不会什么递推式的证明…
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5,MOD=1e9+7;
int n,u,v;
int f[N][2],a[N];
int cnt,head[N];
struct edge{int next,to;}e[N<<1];

inline void add(int u,int v)
{
	cnt++;
	e[cnt].next=head[u];
	e[cnt].to=v;
	head[u]=cnt;
}

//f[u][0]:u的联通块,没有1   f[u][1]:u的联通块,有且只有1个1 
void dfs(int u,int fa)
{
	f[u][a[u]]=1;
	for (register int i=head[u]; i; i=e[i].next)
	if (e[i].to!=fa)
	{
		dfs(e[i].to,u);
		f[u][1]=(f[u][1]*(f[e[i].to][0]+f[e[i].to][1])%MOD+f[u][0]*f[e[i].to][1]%MOD)%MOD;
		//对于f[u][1]来说: 
		//当u所在的区域里已经有1,那么对于它的一棵子树,有1,则断开;没1,则相连
		//当u所在的区域里没有1,那么对于它的一棵子树,有1则相连;没1,则不符合条件 
		f[u][0]=f[u][0]*(f[e[i].to][0]+f[e[i].to][1])%MOD;
		//对于f[u][0]来说:
		//当u所在的区域里已经有1,不符合条件 
		//当u所在的区域里没有1,那么对于它的一棵子树,有1则断开,没1则相连 
	}
}

signed main(){
	scanf("%lld",&n);
	for (register int i=2; i<=n; ++i) scanf("%lld",&u),u++,add(u,i);
	for (register int i=1; i<=n; ++i) scanf("%lld",&a[i]);
	dfs(1,0);
	printf("%lld\n",f[1][1]);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值