【学习笔记】树状数组求逆序对

直接上代码。
时间复杂度与归并排序一致,但是好写多了有木有。

#include <cstdio>
using namespace std;
int a[6]={0,5,2,1,4,3};
int c[6];
int lowbit(int x){
    return x&(-x);
}
void update(int pos,int val){
    while(pos<=5){
        c[pos]+=val;
        pos+=lowbit(pos);
    }
}
int sum(int pos){
    int ret=0;
    while(pos>0){
        ret+=c[pos];
        pos-=lowbit(pos);
    }
    return ret;
}
int main(){
    int n=5,ans=0;
    for(int i=1;i<=n;i++){
        update(a[i],1);
        ans+=i-sum(a[i]);
    }
    printf("%d",ans);
    return 0;
}
posted @ 2016-11-11 17:47  yohanlong  阅读(107)  评论(0编辑  收藏  举报