码迷,mamicode.com
首页 > 其他好文 > 详细

求逆序对 (树状数组版)

时间:2014-08-18 16:30:22      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:os   io   for   amp   size   ef   on   sp   

基本思想和线段树求解逆序数是一样的,前一篇《求逆序对 线段树版》也介绍过,先对输入数组离散,数组里的元素都不相同可以直接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;
}

 

求逆序对 (树状数组版),布布扣,bubuko.com

求逆序对 (树状数组版)

标签:os   io   for   amp   size   ef   on   sp   

原文地址:http://blog.csdn.net/u013923947/article/details/38660155

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!