跳到正文

题解

P11159 题解

Register_int约 1 分钟
原文
文章信息与版本

文章信息

发布
2024年10月3日
收录
2026年8月17日
更新
2026年11月3日
篇幅
约 1 分钟
获赞
15
题目
P11159

版本

  1. v1当前

考虑每一条长链,若长度为 nn,则链内排列的方案为 (n−1)!(n-1)!。

接下来将长链并成树。若长度为 xx 的长链并在长度为 yy 的上,那么必定有 x<yx<y。接上去的位置恰好有 y−xy-x 个,方案数为 y−xy-x。

显然合并过程互不影响,枚举短的计算并到任意一条长链上的方案数,乘起来即可。用前缀和优化可做到 O(n)O(n)。

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

using namespace std;

typedef long long ll;

const int MAXN = 5e5 + 10;
const int mod = 20051131;

int n, cnt[MAXN]; ll ans = 1, sum;

int main() {
	scanf("%d", &n);
	for (int i = 1, x; i <= n; i++) scanf("%d", &x), cnt[x]++;
	sort(cnt + 1, cnt + n + 1, greater<int>());
	for (int i = 1; i <= n; i++) {
		if (!cnt[i]) break;
		for (int j = 1; j < cnt[i]; j++) ans = ans * j % mod;
		if (i > 1) ans = ans * (sum - (ll)(i - 1) * cnt[i]) % mod; sum += cnt[i];
	}
	printf("%lld", ans);
}
原文
存档评论5 条抓取于