1. 程式人生 > 實用技巧 >CF461B Appleman and Tree

CF461B Appleman and Tree

http://codeforces.com/problemset/problem/461/B

感覺這題有點玄學阿。。。。。怎麼說呢。。。

狀態1是x在有黑色的區域裡面,狀態0是隻在白色區域裡面,其實看一眼程式碼就懂了,一直想不出來我很難過。。。。

好菜呀,還要繼續學樹形dp才行阿

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
ll mod = 1e9 + 7;
const int maxn = 2e5 + 11;
vector<int>G[maxn];
void add(int be, int en) {
	G[be].push_back(en);
}
int list[maxn];

ll dp[maxn][3];


int dfs(int x, int fa) {
	for (int i = 0; i < G[x].size(); i++) {
		int p = G[x][i];
		if (p == fa) continue;
		dfs(p, x);

		dp[x][1] = (dp[x][1] * (dp[p][1] + dp[p][0])) % mod + dp[x][0] * dp[p][1] % mod;
		dp[x][1] %= mod;
		dp[x][0] = dp[x][0] * (dp[p][0] + dp[p][1]) % mod;
	}
	return 0;
}

int n;
int main() {
	cin >> n;
	int x, y;
	for (int i = 2; i <= n; i++) {
		cin >> x;
		add(x + 1, i);
		add(i, x + 1);
	}


	for (int i = 1; i <= n; i++) {
		cin >> list[i];
		dp[i][list[i]] = 1;
	}
	dfs(1, -1);
	cout << dp[1][1] << endl;
	return 0;
}