CF1096.F. Inversion Expectation(树状数组)
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i,j) such that i>j and ai<aj. For example, a permutation [4,1,3,2] contains 4 inversions: (2,1), (3,1), (4,1), (4,3)
.
You are given a permutation p
of size n. However, the numbers on some positions are replaced by −1. Let the valid permutation be such a replacement of −1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation 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 P
where P and Q are non-negative integers and Q≠0. Report the value of P
.
InputThe first line contains a single integer n
(1≤n≤2⋅105) — the length of the sequence.
The second line contains n
integers p1,p2,…,pn (−1≤pi≤n, pi≠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 P
where P and Q are non-negative integers and Q≠0. Report the value of P.
Examples3 3 -1 -1
499122179
2 1 2
0
2 -1 -1
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; }