Sort it(树状数组逆序对)

http://acm.hdu.edu.cn/showproblem.php?pid=2689

#include<bits/stdc++.h>
#define low(x) (x&(-x))
using namespace std;
const int maxn=1e5+5;
typedef long long ll;
int a[maxn];
int n;
void add(int i,int d){
    for(;i>0;i-=low(i))
        a[i]+=d;
}
int ask(int i){
    int cnt=0;
    for(;i<=n;i+=low(i))
        cnt+=a[i];
    return cnt;
}
int main(){
    //freopen("in","r",stdin);
    while(scanf("%d",&n)!= EOF) {
        ll ans = 0;
        memset(a,0,sizeof(a));
        for (int i = 1; i <= n; i++) {
            int num;
            scanf("%d", &num);
            ans += ask(num);
            add(num, 1);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xcfxcf/p/12979644.html