求逆序对 (树状数组版)

基本思想和线段树求解逆序数是一样的,前一篇《求逆序对 线段树版》也介绍过,先对输入数组离散,数组里的元素都不相同可以直接hash,存在相同的数话可以采用二分。

离散化后对于每个f[i],找到f[i]+1~ n中的个数,也就是到i这个位置,一共有多少比f[i]大的数,统计之后在将f[i]的位置上的数量加1。

这样一来统计的就是类似a[i]~n的和,可以想象成 把树状数组反过来统计,即统计的时候加lowbit,更新的时候减lowbit。


还是 以POJ 2299为例。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <stack>
#include <cctype>
#include <algorithm>
#define lson o<<1, l, m
#define rson o<<1|1, m+1, r
using namespace std;
typedef long long LL;
const int maxn = 500050;
const int mod = 99999997;
const int MAX = 0x3f3f3f3f;
int n, tmp, f[maxn];
LL c[maxn];
struct C {
    int num, pos;
}in[maxn];
bool cmp(C x, C y) {
    return x.num < y.num;
}
int main()
{
    while(cin >> n, n) {
        for(int i = 1; i <= n; i++) {
            scanf("%d", &in[i].num);
            in[i].pos = i;
        }
        sort(in+1, in+1+n, cmp);
        LL sum = 0;
        memset(c, 0, sizeof(c));
        for(int i = 1; i <= n; i++) f[ in[i].pos ] = i;
        for(int i = 1; i <= n; i++) {
            for(int j = f[i]+1; j <= n; j += j&(-j))
                sum += c[j];
            for(int j = f[i]; j > 0; j -= j&(-j))
                c[j]++;
        }
        cout << sum << endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值