A permutation of size )
.
You are given a permutation p
of size n
.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of Q
where )
.
InputThe first line contains a single integer n
(5) — the length of the sequence.
The second line contains n
integers 0) — the initial sequence.
It is guaranteed that all elements not equal to 1
are pairwise distinct.
OutputPrint a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of Q
where ).
ExamplesInput
3 3 -1 -1
Output
499122179
Input
2 1 2
Output
0
Input
2 -1 -1
Output
499122177
题意:给定一个数组,是一个N的排列,其中有些未知没有填数,让你补全,问逆序对的期望是多少。
思路:就是枚举几种情况就好了。
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=a;i<=b;i++) #define ll long long using namespace std; const int maxn=1000010; const int Mod=998244353; int vis[maxn],a[maxn],b[maxn],cnt,sum[maxn],fac[maxn],ans,v,tot,N; int qpow(int a,int x){ int res=1; while(x){ if(x&1) res=1LL*res*a%Mod; a=1LL*a*a%Mod; x>>=1; } return res; } void add(int x){ for(;x<=N;x+=(-x)&x) sum[x]++;} int query(int x){ int res=0; for(;x;x-=(-x)&x) res+=sum[x]; return res; } int main() { scanf("%d",&N); rep(i,1,N) { scanf("%d",&a[i]); if(a[i]!=-1) vis[a[i]]=1; } rep(i,1,N) if(!vis[i]) b[++cnt]=i; //空位 sort(b+1,b+cnt+1);fac[0]=1; rep(i,1,cnt) fac[i]=1LL*fac[i-1]*i%Mod; rep(i,1,N){ if(a[i]!=-1){ int Less=query(a[i]); ans=(ans+1LL*(tot-Less)*fac[cnt]%Mod)%Mod; //已知+已知 int pos=lower_bound(b+1,b+cnt+1,a[i])-b; pos--; ans=(ans+1LL*pos*(cnt-v)%Mod*fac[cnt-1]%Mod)%Mod; //已知+未知 ans=(ans+1LL*(cnt-pos)*v%Mod*fac[cnt-1]%Mod)%Mod;//未知+已知 tot++; add(a[i]); } else v++; } ans=(ans+1LL*cnt*(cnt-1)%Mod*fac[cnt]%Mod*qpow(4,Mod-2)%Mod)%Mod; //未知+未知 fac[cnt]=qpow(fac[cnt],Mod-2); printf("%d\n",1LL*ans*fac[cnt]%Mod); return 0; }