461B - Appleman and Tree - CodeForces Solution


dfs and similar dp trees *2000

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 5, MOD = 1e9 + 7;

int dp[maxn][2], c[maxn];
vector<int> adj[maxn];
//dp[u][c] = quantas maneiras ha de resolver o problema tal que a raiz (u)
// esta numa componente de soma c

int inv(int a){
	int rt = 1, xp = MOD-2;
	while(xp){
		if(xp&1) rt = rt*a%MOD;
		xp>>=1;
		a = a*a%MOD;
	}

	return rt;
}

void solve(int u){
	if(adj[u].size()==0){
		dp[u][1] = c[u];
		dp[u][0] = !c[u];
		return;
	}

	int total = 1;
	for(int v : adj[u]) solve(v), total = total*((dp[v][1]+dp[v][0])%MOD)%MOD;
	dp[u][c[u]] = total;
	//se meu valor eh x, entao eu posso n conectar com todos os 1's
	//e conectar com todos os 0's e meu valor continuara o mesmo

	if(!c[u])
		for(int v : adj[u])
			dp[u][1] = (dp[u][1]+(dp[v][1]*(total*inv((dp[v][1]+dp[v][0])%MOD)%MOD)%MOD)%MOD)%MOD;
	//se meu valor eh 0, eu posso conectar com cada 1 individualmente e
	//nao alterar minha soma para todos os outros filhos
}

int32_t main(){
	int n; cin >> n;
	for(int i = 1; i < n; i++){
		int a; cin >> a;
		adj[a].push_back(i);
	}
	for(int i = 0; i < n; i++) cin >> c[i];

	solve(0);

	cout << dp[0][1] << '\n';
}


Comments

Submit
0 Comments
More Questions

454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection