HDOJ-2689 Sort it

这道题就是求逆序数。用树状数组来求解。输入一个数求此时关于这个点的逆序数 = i- Query(a).累加求和.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

#define maxn 1005 

int c[maxn], n;
void Update(int m, int p){

    while(m <= n){

        c[m] += p;
        m += m & -m;
    }
}
int Query(int m){

    int sum = 0;
    while(m){

        sum += c[m];
        m -= m & -m; 
    }

    return sum;
}

int main(){

    //freopen("in.txt", "r", stdin);
    while(cin >> n){

        memset(c, 0, sizeof(c));
        int sum = 0;
        for(int i = 1; i <= n; i++){

            int a;
            scanf("%d", &a);
            Update(a, 1);
            sum += i - Query(a);
        }
        cout << sum << endl;
    }

    return 0;
}

你可能感兴趣的:(HDOJ-2689 Sort it)