luogu P1908 逆序对 |树状数组

题目描述

猫猫TOM和小老鼠JERRY最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。最近,TOM老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中ai>aj且i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。
Update:数据已加强。

输入格式

第一行,一个数n,表示序列中有n个数。

第二行n个数,表示给定的序列。序列中每个数字不超过10^9

输出格式

给定序列中逆序对的数目。

说明/提示

对于25%的数据,n≤2500

对于50%的数据,n≤4×10^4

对于所有数据,n≤5×10^5

请使用较快的输入输出

应该不会n方过50万吧 by chen_zhe


#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
const int N=5e5+10;
#define int long long
using namespace std;
int c[N],n,a[N],b[N];
inline void add(int x,int y){
    for(;x<=n;x+=x&(-x))c[x]+=y;
}
inline int sum(int x){
    int ans=0;
    for(;x;x-=x&(-x))ans+=c[x];
    return ans;
}
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        b[i]=a[i];
    }
    sort(b+1,b+1+n);
    int len=unique(b+1,b+1+n)-b-1;
    for(int i=1;i<=n;i++)
    a[i]=lower_bound(b+1,b+1+len,a[i])-b;
    int ans=0;
    for(int i=n;i>=1;i--){
        ans+=sum(a[i]-1);
        add(a[i],1);
    }
    cout<<ans<<endl;
}

猜你喜欢

转载自www.cnblogs.com/naruto-mzx/p/11848650.html