SGU 180 Inversions 逆序数

--------------

int n;
int a[maxn];
int b[maxn];

struct BIT{
    int n;
    int tree[maxn];
    void init(int n){
        this->n=n;
        memset(tree,0,sizeof(tree));
    }
    int lowbit(int x){
        return x&(-x);
    }
    void add(int x,int val){
        for (int i=x;i<=n;i+=lowbit(i)) tree[i]+=val;
    }
    int query(int x){
        int ret=0;
        for (int i=x;i>0;i-=lowbit(i)) ret+=tree[i];
        return ret;
    }
    //离散 p=lower_bound(b+1,b+n+1,a[i])-b;
    //逆序数 x=(i-1)-query(p);add(p,1);
}bt;

int main(){
    cin>>n;
    bt.init(n);
    for (int i=1;i<=n;i++){
        cin>>a[i];
        b[i]=a[i];
    }
    sort(b+1,b+1+n);
    LL sum=0;
    for (int i=1;i<=n;i++){
        int p=lower_bound(b+1,b+n+1,a[i])-b;
        int x=i-1-bt.query(p);
        bt.add(p,1);
        sum+=x;
    }
    cout<<sum<<endl;
	return 0;
}


--------------

你可能感兴趣的:(SGU 180 Inversions 逆序数)