题意
给定一棵 \(n\) 个节点的线段树。
任意黑白染色,求每个点被染成黑色且黑色点组成连通块的方案数。
Sol
考虑换根dp,钦定当前点作为根节点。
- \(f_i\) 表示当前子树内的方案数。
- \(g_i\) 表示子树外的方案数。
\(f\) 的转移显然是 \(f_u = \prod f_v + 1\)。
考虑 \(g\) 的转移。\(fa\) 子树外的贡献,以及 \(x\) 的兄弟儿子的贡献。
对于前者固然为 \(g_{fa}\),后者考虑预处理前缀积后缀积。
需要注意的是,两者都是只有当 \(fa\) 被选时才会有贡献,所以 \(g_{fa}\) 不 \(+1\)。
\(g_u = 1 + g_{fa} \times \prod f_v + 1, v \in {brother}\)。
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#define int long long
using namespace std;
#ifdef ONLINE_JUDGE
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;
#endif
int read() {
int p = 0, flg = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flg = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
p = p * 10 + c - '0';
c = getchar();
}
return p * flg;
}
void write(int x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9) {
write(x / 10);
}
putchar(x % 10 + '0');
}
const int N = 1e5 + 5, M = 2e5 + 5;
int mod;
namespace G {
array <int, N> fir;
array <int, M> nex, to;
int cnt;
void add(int x, int y) {
cnt++;
nex[cnt] = fir[x];
to[cnt] = y;
fir[x] = cnt;
}
}
array <int, N> f, g;
array <int, N> fa;
void dfs1(int x) {
f[x] = 1;
for (int i = G::fir[x]; i; i = G::nex[i]) {
if (G::to[i] == fa[x]) continue;
fa[G::to[i]] = x;
dfs1(G::to[i]);
f[x] = f[x] * (f[G::to[i]] + 1) % mod;
}
}
array <int, N> tp;
void dfs2(int x) {
int cnt = 0;
for (int i = G::fir[x]; i; i = G::nex[i]) {
if (G::to[i] == fa[x]) continue;
cnt++, tp[cnt] = f[G::to[i]] + 1;
}
tp[cnt + 1] = 1;
for (int i = cnt; i; i--)
tp[i] = tp[i] * tp[i + 1] % mod;
cnt = 0;
int kp = 1;
for (int i = G::fir[x]; i; i = G::nex[i]) {
if (G::to[i] == fa[x]) continue;
cnt++;
g[G::to[i]] = g[x] * kp % mod * tp[cnt + 1] % mod + 1;
kp = kp * (f[G::to[i]] + 1) % mod;
}
for (int i = G::fir[x]; i; i = G::nex[i]) {
if (G::to[i] == fa[x]) continue;
dfs2(G::to[i]);
}
}
signed main() {
int n = read();
mod = read();
for (int i = 2; i <= n; i++) {
int x = read(), y = read();
G::add(x, y), G::add(y, x);
}
g[1] = 1;
dfs1(1), dfs2(1);
for (int i = 1; i <= n; i++) write(f[i] * g[i] % mod), puts("");
return 0;
}
标签:fir,DPV,cnt,int,Subtree,tp,fa,mod
From: https://www.cnblogs.com/cxqghzj/p/17851018.html