树状数组逆序对

来源:互联网 发布:Sql中not in的效率 编辑:程序博客网 时间:2024/04/30 03:32
#include<iostream>#include<cstdio>#include<cstdlib>#include<algorithm>#define LL long longusing namespace std;LL a[500000],c[500000]={0}; LL n,ans=0,rr=0;struct kl{    LL x,pos;}re[500000];bool comp(kl q,kl y) {return (q.x<y.x);}LL lowbit(LL x){    return x&-x;}LL sum(LL x){    LL as=0;    while (x>0)    {        as+=c[x];        x-=lowbit(x);    }    return as;}void add(LL x){    while (x<=n)    {        c[x]++;        x+=lowbit(x);    }}int main(){    scanf ("%lld",&n);    for (int o=1;o<=n;++o)    {        scanf ("%lld",&re[o].x);        re[o].pos=o;    }    sort(re+1,re+n+1,comp);    for (int i=1;i<=n;++i)    {        if (re[i].x!=re[i-1].x) rr++;        a[re[i].pos]=rr;    }    for (int i=1;i<=n;++i)    {        add(a[i]);        ans+=i-sum(a[i]);        //cout<<sum(a[i])<<endl;    }    cout<<ans;    return 0;   }
0 0
原创粉丝点击