跳到正文

题解

P8329 [ZJOI2022] 树

JoshAlMan约 4 分钟
原文
文章信息与版本

文章信息

发布
2022年5月3日
收录
2026年8月6日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
22
题目
P8329

版本

  1. v1当前

考虑假设现在确定了哪个叶子集合是第一棵的,剩下是第二棵。那就是要算恰好第棵叶子集合是这个的方案数,钦定一个集合是叶子好做的,第一棵树就是每个点前面非叶子个数乘起来(第二颗树类似),所以可以选一个不能是叶子集合的容斥。

所以大概就是类似这样的形式:

(∑(−1)∣s∣×w(s))(∑(−1)∣t∣×w(t))(\sum_{}(-1)^{|s|} \times w(s))(\sum_{}(-1)^{|t|} \times w(t))

然后你展开发现同样是行的,就意味着可以一起容斥,其实很显然。。

所以就 dp,决定每个点是哪个叶子的同时,另一颗树可以选择也视为叶子容斥。

考虑按编号从小到大决定,fx,yf_{x, y} 表示目前位置(包括现在这个)之前第一棵树前面有 xx 非叶子,目前位置之后(不包括这个)第二棵树有 yy 个非叶子。

初始 f1,i=if_{1, i} = i,终止 ans=∑ifi,1×ians = \sum_{i} f_{i, 1} \times i

每次迭代加一个,设之前的是 f′f',考虑对当前 ff 的贡献:

  • 考虑当前叶子给第一棵树
    • 钦定第二棵树是叶子容斥: −fx,y′×x×y→fx,y-f'_{x,y} \times x \times y \rightarrow f_{x,y}
    • 不钦定第二棵树是叶子: fx,y′×x×(y−1)→fx,y−1f'_{x,y} \times x \times (y-1) \rightarrow f_{x,y-1}
  • 考虑第二棵树叶子集合是这个
    • 钦定第一棵树是叶子容斥: −fx,y′×x×y→fx,y-f'_{x,y} \times x \times y \rightarrow f_{x,y} (哈哈,和刚才是一样的,神奇哦
    • 不钦定:fx,y′×x×y→fx+1,yf'_{x,y} \times x \times y \rightarrow f_{x+1,y}

复杂度 O(n3)O(n^3)。

代码应该是对的吧,,计数题诶。

C++
// SKyqwq
#include <bits/stdc++.h>

#define fi first
#define se second
#define mp make_pair
#define pb push_back

using namespace std;

typedef pair<int, int> PII;
typedef long long LL;

template <typename T> bool inline chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
template <typename T> bool inline chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }

template <typename T> void inline read(T &x) {
	x = 0; int f = 1; char s = getchar();
	while (s > '9' || s < '0') { if (s == '-') f = -1; s = getchar(); }
	while (s <= '9' && s >= '0') x = x * 10 + s - '0', s = getchar();
	x *= f;
}

const int N = 505;

int P, n, f[N][N], g[N][N], ans;

void inline add(int &x, int y) {
	x += y;
	if (x >= P) x -= P;
}

void inline del(int &x, int y) {
	x -= y;
	if (x < 0) x += P;
}

int main() {
	read(n), read(P);
	for (int i = 1; i <= n; i++) f[1][i] = i;
	for (int i = 2; i <= n; i++) {
		ans = 0;
		for (int j = 1; j <= n; j++) add(ans, 1ll * f[j][1] * j % P);
		printf("%d\n", ans);
		memcpy(g, f, sizeof f);
		memset(f, 0, sizeof f);
		for (int x = 1; x <= n; x++) {
			for (int y = 1; y <= n; y++) {
				if (!g[x][y]) continue;
				int w = g[x][y];
				add(f[x][y - 1], 1ll * w * x % P * (y - 1) % P);
				del(f[x][y], 1ll * w * x % P * y % P);
				add(f[x + 1][y], 1ll * w * x % P * y % P);
				del(f[x][y], 1ll * w * x % P * y % P);
			}
		}
	}
	
	return 0;
}
原文
存档评论19 条抓取于