[CF461B] Appleman and Tree - 树形dp
作者:互联网
## [CF461B] Appleman and Tree - 树形dp
### Description
给你一棵树,有的点是黑色的有的点是白色的,把树分成若干个联通块使得每个联通块有且仅有一个黑点,问有多少种分法。
### Solution
树形 dp,转移时整体枚举一下边割不割即可
$f[i]$ 表示处理掉 i 子树,并且无法上传,$h[i]$ 表示处理掉 i 子树,并且可以上传
``` cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
int qpow(int p, int q)
{
return (q & 1 ? p : 1) * (q ? qpow(p * p % mod, q / 2) : 1) % mod;
}
int inv(int p)
{
return qpow(p, mod - 2);
}
int n, a[N], f[N], h[N];
vector<int> g[N];
void dfs(int p)
{
int mul_fh = 1;
for (int q : g[p])
{
dfs(q);
(mul_fh *= f[q] + h[q]) %= mod;
}
if (a[p] == 0)
f[p] += mul_fh;
if (a[p])
h[p] += mul_fh;
else
for (int q : g[p])
h[p] += h[q] * mul_fh % mod * inv(f[q] + h[q]) % mod;
f[p] %= mod;
h[p] %= mod;
}
signed main()
{
ios::sync_with_stdio(false);
cin >> n;
for (int i = 2; i <= n; i++)
{
int x;
cin >> x;
++x;
g[x].push_back(i);
}
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
dfs(1);
for (int i = 1; i <= n; i++)
{
// cout << "i=" << i << "\t" << f[i] << "\t" << h[i] << endl;
}
cout << h[1] % mod << endl;
}
标签:int,Tree,dfs,Appleman,fh,mul,dp,mod 来源: https://www.cnblogs.com/mollnn/p/14396579.html