AtCoder Grand Contest 023 E - Inversions

Description

Given a sequence of length \(n\) \(A_i\) , find all permutations of length \(n\) \(P\) , satisfying \(P_i<=A_i\) , find all satisfying conditions \ (P\) sum of inverse logarithms

Solution

Let \(c[k]\) represent the number of \(A_i>=k\) , then for all \(c[k]>=(n-k+1)\) , it is illegal if not satisfied
. \(c[k]\) becomes \(c[k]-(nk),\) The total solution is \(\Pi c[k]\) considering the contribution
of reverse order to \((i,j)\)
If \(A_i<=A_j\) is satisfied , then change \(A_j\) into \(A_i\) , then \((i,j)\) as the number of reversed pairs is the number of legal arrangements divided by \(2\)
After turning \(A_j\) into \(A_i\) , \([A_i+1,A_j]\) in the interval \(c\) will be reduced by \(1\) , which can be maintained A prefix product \(\frac{c_i-1}{c_i}\) can be \(O(1)\)Calculate the contribution after replacement,
then you can maintain the contribution of each pair of numbers in a tree-like array

For the case of \(A[i]>A[j]\) , the complement is converted, the general scheme - replace \(A_i\) with the scheme of \(A_j\) , and then do the same as above. span

#include<bits/stdc++.h>
using namespace std;
template<class T>void gi(T &x){
    int f;char c;
    for(f=1,c=getchar();c<'0'||c>'9';c=getchar())if(c=='-')f=-1;
    for(x=0;c<='9'&&c>='0';c=getchar())x=x*10+(c&15);x*=f;
}

const int N=2e5+10,mod=1e9+7;
inline int qm(int x,int k){
    int sum=1;
    while(k){
        if(k&1)sum=1ll*sum*x%mod;
        x=1ll*x*x%mod;k>>=1;
    }
    return sum;
}
int n,a[N],c[N],v0[N],R[N],tr[N],S;
inline void add(int x,int t){
    for(int i=x;i<=n;i+=(i&(-i)))tr[i]=(tr[i]+t)%mod;
}
inline int qry(int x){
    int ret=0;
    for(int i=x;i>=1;i-=(i&(-i)))ret=(ret+tr[i])%mod;
    return ret;
}
int main(){
  freopen("pp.in","r",stdin);
  freopen("pp.out","w",stdout);
  cin>>n;
  for(int i=1;i<=n;i++)gi(a[i]),c[a[i]]++;
  for(int i=n-1;i>=1;i--)c[i]+=c[i+1]-1;
  for(int i=1;i<=n;i++)if(c[i]<=0)return puts("0"),0;
  v0[0]=S=1;
  for(int i=1;i<=n;i++){
      v0[i]=1ll*v0[i-1]*(c[i]>1?c[i]-1:1)%mod*qm(c[i],mod-2)%mod;
      S=1ll*S*c[i]%mod;
  }
  R[n]=n;
  for(int i=n-1;i>=1;i--)R[i]=c[i+1]>1?R[i+1]:i;
  int ans=0,t;
  //A[i]<=A[j]
  for(int i=n;i>=1;i--){
      t=(qry(R[a[i]])-qry(a[i]-1)+mod)%mod;
      ans=(ans+1ll*t*qm(v0[a[i]],mod-2))%mod;
      add(a[i],v0[a[i]]);
  }
  //A[i]>A[j]
  R[1]=1;
  memset(tr,0,sizeof(tr));
  for(int i=2;i<=n;i++)R[i]=c[i]>1?R[i-1]:i;
  for(int i=n;i>=1;i--){
      t=(qry(a[i]-1)-qry(R[a[i]]-1)+mod)%mod;
      ans=(ans-1ll*t*v0[a[i]]%mod+mod)%mod;
      add(a[i],qm(v0[a[i]],mod-2));
  }
  ans=1ll*ans*qm(2,mod-2)%mod;
  memset(tr,0,sizeof(tr));
  for(int i=1;i<=n;i++){
      ans=(1ll*ans+i-1-qry(a[i])+mod)%mod;
      add(a[i],1);
  }
  ans=1ll*ans*S%mod;
  cout<<ans<<endl;
  return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325100371&siteId=291194637