P8329 [ZJOI2022] 树

· · 题解

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

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

(\sum_{}(-1)^{|s|} \times w(s))(\sum_{}(-1)^{|t|} \times w(t))

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

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

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

初始 f_{1, i} = i,终止 ans = \sum_{i} f_{i, 1} \times i

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

复杂度 O(n^3)。

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

// 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;
}