跳到正文

题解

世界线

Xuan_tmp约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月8日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 3 分钟
获赞
7
题目
P14639

版本

  1. v2当前
  2. v1

upd:写的时候过于脑残然后所有组合数都写反了,因此修正。


考虑题目的要求,是将序列重排后可以分成两个子序列,一个不降,一个不升,所以我们考虑第一位放什么。

设最终的序列中,第一位是 xx,那么最终序列的形态就是比 xx 大的数排成不降序列,比 xx 小的数排成不增序列,而所有等于 xx 的会全部排进两个序列中的一个。

我们先不考虑相等的那部分,设比 xx 大的数有 pp 个,比 xx 小的数有 qq 个,那么排列的方案数就是 (p+qp){p+q}\choose p。

相等的那部分考虑容斥,设序列中除去第一位外等于 xx 的数有 rr 个,将它们划进不降序列方案数为 (n−1p+r)n-1 \choose p+r,划进不增序列方案数为 (n−1q+r)n-1 \choose q+r,其中重复的部分为这 rr 个数构成序列的前缀因此可以被划分到任意一个序列中,方案数为 (p+qp)p+q\choose p。

因此以 xx 为第一位时的方案数是 (n−1p+r)+(n−1q+r)−(p+qp){n-1 \choose p+r}+{n-1 \choose q+r}-{p+q\choose p},p,q,rp,q,r 都很好预处理,直接对于所有 xx 求该式的和即可。

code

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=1000005,mod=998244353;
int n,cnt[N],pre[N],fac[N],inv[N];
int ksm(int a,int q){
	int res=1;
	while(q){
		if(q&1)res=res*a%mod;
		a=a*a%mod;
		q>>=1;
	}
	return res;
}
int C(int n,int m){
	if(n<m||m<0)return 0;
	return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
signed main() {
	fac[0]=1;
	for(int i=1;i<N;i++)fac[i]=fac[i-1]*i%mod;
	inv[N-1]=ksm(fac[N-1],mod-2);
	for(int i=N-1;i>0;i--)inv[i-1]=inv[i]*i%mod;
	cin>>n;
	for(int i=1;i<=n;i++){
		int x;cin>>x;
		cnt[x]++;
	}
	for(int i=1;i<=n;i++)pre[i]=pre[i-1]+cnt[i];
	int ans=0;
	for(int i=1;i<=n;i++)if(cnt[i])ans=(ans+C(n-1,pre[i-1])+C(n-1,n-pre[i])-C(n-cnt[i],pre[i-1])+mod)%mod;
	cout<<ans<<'\n';
}
原文
存档评论4 条抓取于