Educational Codeforces Round 57 (Rated for Div. 2) F. Inversion Expectation(组合数学+期望)

题目链接: http://codeforces.com/contest/1096/problem/F

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<ll,ll>
#define mk(x,y) make_pair(x,y)
const int  maxn =2e5+5;
const int mod=998244353;
const int inv2=499122177;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
int n,a[maxn],cnt1=0,tot=0;
int tmp[maxn],cnt=0;
///bit
int tree[maxn];
void add(int x,int v){for(;x<maxn;tree[x]+=v,x+=(x&-x));}
int sum(int x){int ret=0;for(;x>0;ret+=tree[x],x-=(x&-x));return ret;}
/*
题目大意:给定一个序列,里面有-1填充,
也有原本的几个数字,问满足这种性质的排列其逆序对个数期望值是多少(不考虑矛盾的排序序列)。

一道组合数学题,先计算总体能产生的逆序对个数,
先是序列中原本填充好的数字产生的个数,但要乘上-1的个数的阶乘(ans1)
再其次就是-1位置填充的产生的逆序对个数,不难计算出对于长度为n
的有序序列其全排列的逆序对个数是:(n)(n-1)/2*(n!)。
具体计算过程是:考虑任意两个数,先是选两个,然后两个数的位置有(n)*(n-1)/2,
剩余长度排列是(n-2)!。

再考虑-1和原本位置的数字产生的逆序对个数,假设我们得知了当前比a[i]大的且没有出现在序列中的数有x个,
前面出现的-1有y个,那么产生的逆序对个数是:x*y*((tot-1)!),tot是-1的总个数。

时间复杂度:O(nlogn)。
*/
ll ans1=0,ans2=1,ans3=0;
ll fac[maxn];
int main(){
    fac[0]=1LL;rep(i,1,maxn) fac[i]=fac[i-1]*i%mod;
    cin>>n;
    rep(i,0,n){
         cin>>a[i];
         if(a[i]!=-1) tmp[cnt++]=a[i];
         else tot++;
    }
    sort(tmp,tmp+cnt);
    rep(i,0,n){
        if(a[i]==-1) cnt1++,ans2=ans2*1LL*cnt1%mod;///
        else{
            ans1=( ans1 + 1LL*( sum(maxn-1)-sum(a[i]) ) )%mod;///统计原本的逆序对,最后需要乘上阶乘
            add(a[i],1);
            int tp=lower_bound(tmp,tmp+cnt,a[i])-tmp;
            ans3=( ans3+(a[i]-1-1LL*tp)*(tot-cnt1)%mod*fac[max(0,tot-1)]%mod )%mod;///累加-1和原本的序列产生的逆序对
            ans3=( ans3+(n+1LL*tp+1-cnt-a[i])*cnt1%mod*fac[max(0,tot-1)]%mod )%mod;
        }
    }
    ans2=ans2*cnt1%mod*(cnt1-1)%mod*inv2%mod;
    if(cnt1<=1) ans2=0LL;
    else ans2=ans2*inv2%mod;
    ans1=ans1*fac[cnt1]%mod;
    ans1=(ans1+ans2)%mod;
    ans1=(ans1+ans3)%mod;
    ans1=ans1*powmod(fac[cnt1],mod-2)%mod;
    cout<<ans1<<endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值