SUG 180 Inversions(树状数组+离散化)

题意:

求逆序数的个数,因为题目没说是从1~n,所以要离散化。

心得:

这题wa了好多次,是因为询问时 query(order[i]-1) 写错成 query(order[i])。

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef __int64 ll;
const ll INF = 0x3f3f3f3f;
const ll N = 70000;
struct Node {
    ll num, id;
}node[N];
ll C[N];
ll n, order[N];
bool cmp(Node a, Node b) { //按照数字排序
    return a.num < b.num;
}
ll lowbit(ll x) {
    return x & (-x);
}
ll query(ll x) {
    ll ret = 0;
    while(x > 0) {
        ret += C[x];
        x -= lowbit(x);
    }
    return ret;
}
void add(ll x, ll d) {
    while(x <= n) {
        C[x] += d;
        x += lowbit(x);
    }
}
void discrete() { //离散化
    sort(node+1, node+1+n, cmp);
    order[node[1].id] = 1;
    for(ll i = 2; i <= n; i++) {
        if(node[i].num != node[i-1].num)
            order[node[i].id] = i;
        else
            order[node[i].id] = order[node[i-1].id];
    }
}
int main() {
    scanf("%I64d", &n);
    memset(C, 0, sizeof(C));
    for(ll i = 1; i <= n; i++) {
        scanf("%I64d", &node[i].num);
        node[i].id = i;
    }
    discrete();
    ll ans = 0;
    for(ll i = n; i >= 1; i--) {
        ans += query(order[i]-1);
        add(order[i], 1);
    }
    printf("%I64d\n", ans);
    return 0;
}

你可能感兴趣的:(180,sug)