题面
题解
设\(lim=(n-1)/2\)(这里是下取整),那么\(x\)位置的值最大不能超过\(lim\),而\(y\)处的值不能小于\(y\),于是有\[Ans=\sum_{i=1}^{lim}\sum_{j=2 i+1}^n(y-2)!{j-2\choose y-2}(n-y)!\]
上式的意思是,枚举\(x\)处的值\(i\)和\(y\)处的值\(j\),那么放在\(y\)前面的数都不能大于\(j\),要从除了\(i,j\)之外的剩下\(j-2\)个数中选出\(y-2\)个,因为顺序无所谓要乘上\((y-2)!\),这后面的数也随便放,所以再乘上一个\((n-y)!\)
\((y-2)!\)和\((n-y)!\)都是常数,提到前面来然后先考虑如何快速计算\(\sum_{j=2i+1}^n{j-2\choose y-2}\),可以拆成两个前缀和相减的形式,为\({n-1\choose y-1}-{2i-1\choose y-1}\),这样我们就可以做到单次询问\(O(n)\)的复杂度了
考虑继续化简,我们要快速计算\[\sum_{i=1}^{lim}({n-1\choose y-1}-{2i-1\choose y-1})\]
前面是个定值,提出来,于是现在需要快速计算\(\sum_{i=1}^{lim}{2i-1\choose y-1}\)
这样看不太清楚,我们把它展开来\[A_{y-1}={1\choose y-1}+{3\choose y-1}+...+{2lim-1\choose y-1}\]
然后考虑另外一个式子\[B_{y-1}={2\choose y-1}+{4\choose y-1}+...+{2lim\choose y-1}\]
有\[A_{y-1}+B_{y-1}={2lim+1\choose y}\]
然后惊奇的发现,\(A\)和\(B\)之间也有联系\[A_{y-1}+A_{y-2}=B_{y-1}\]
所有\[A_{y-1}=\frac{{2lim+1\choose y}-A_{y-2}}{2}\]
边界条件为\(A_0=lim\)
于是\(A\)就可以\(O(n)\)递推了
然后我们就算完了,时间复杂度为\(O(n+q)\)
//minamoto
#include<bits/stdc++.h>
#define R register
#define fp(i,a,b) for(R int i=a,I=b+1;i<I;++i)
#define fd(i,a,b) for(R int i=a,I=b-1;i>I;--i)
#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
using namespace std;
char buf[1<<21],*p1=buf,*p2=buf;
inline char getc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
int read(){
R int res,f=1;R char ch;
while((ch=getc())>'9'||ch<'0')(ch=='-')&&(f=-1);
for(res=ch-'0';(ch=getc())>='0'&&ch<='9';res=res*10+ch-'0');
return res*f;
}
char sr[1<<21],z[20];int K=-1,Z=0;
inline void Ot(){fwrite(sr,1,K+1,stdout),K=-1;}
void print(R int x){
if(K>1<<20)Ot();if(x<0)sr[++K]='-',x=-x;
while(z[++Z]=x%10+48,x/=10);
while(sr[++K]=z[Z],--Z);sr[++K]='\n';
}
const int N=1e6+5,P=998244353,inv2=499122177;
inline int add(R int x,R int y){return x+y>=P?x+y-P:x+y;}
inline int dec(R int x,R int y){return x-y<0?x-y+P:x-y;}
inline int mul(R int x,R int y){return 1ll*x*y-1ll*x*y/P*P;}
int ksm(R int x,R int y){
R int res=1;
for(;y;y>>=1,x=mul(x,x))if(y&1)res=mul(res,x);
return res;
}
int fac[N],inv[N],A[N];
int n,res,q,x,y,m;
inline int C(R int n,R int m){return m>n?0:1ll*fac[n]*inv[m]%P*inv[n-m]%P;}
int main(){
// freopen("testdata.in","r",stdin);
freopen("permutation.in","r",stdin);
freopen("permutation.out","w",stdout);
n=read(),q=read();
inv[0]=fac[0]=1;fp(i,1,n)fac[i]=mul(fac[i-1],i);
inv[n]=ksm(fac[n],P-2);fd(i,n-1,1)inv[i]=mul(inv[i+1],i+1);
m=(n-1)/2;A[0]=m;fp(i,1,n)A[i]=mul(dec(C(2*m+1,i+1),A[i-1]),inv2);
while(q--){
x=read(),y=read(),res=0;
// fp(j,1,(n-1)/2)res=add(res,dec(C(n-1,y-1),C(2*j-1,y-1)));
res=mul(m,C(n-1,y-1)),res=dec(res,A[y-1]);
res=mul(res,fac[y-2]),res=mul(res,fac[n-y]);
print(res);
}
return Ot(),0;
}
原文地址:https://www.cnblogs.com/bztMinamoto/p/10276665.html