POJ 2299(树状数组求逆序对)

Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 62722 Accepted: 23367

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 
9 1 0 5 4 ,

Ultra-QuickSort produces the output 
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

Source

.
题意:给出n个数字,求出这n个数字里边的逆序对数目。首先解释逆序对。譬如:3 2 1,那么有逆序对(3,2),(3,1),(2,1)。
就是按照输入顺序,有数对(ai,aj),其中i<j并且ai>aj。下面回到正题,首先这道题可以用归并排序来做,这里介绍树状数组的写法。没有树状数组基础的可以先百度了解一下。我们知道,假如有a1,a2,a3,a4,a5。那么假如判断a3,我们知道a3在第3个位置,那么如果以a3为结尾,最多有2个逆序对,然后我们再找出1~2这段区间中比a3小的数的个数k(比a3小的数肯定不能构成逆序对),这里就是树状数组的区间求和问题了,那么2-k就是a3这个位置能够构成的逆序对数,然后再用树状数组往后面更新a3,表示a3进入树状数组。然后判断a4能够构成的逆序对数也跟a3一样。另外,这里由于ai的范围太大,我们不能直接开那么大的数组,注意到N只有500000;那么我们可以先将ai离散化,离散化之后,再用二分找出位置pos(注意这里的pos应该≥1),这样离散化保证数之间相对大小是不变的,然后就是上边树状数组那部分了。

代码:

#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;

int sum[500005];
int a[500005];
int b[500005];
int n;
int lowbit(int x){
    return x&(-x);
}

void update(int x){
    while(x<=n){
        sum[x]+=1;
        x+=lowbit(x);
    }
}

long long getsum(int x){
    long long ans=0;
    while(x>0){
        ans+=sum[x];
        x-=lowbit(x);
    }
    return ans;
}

int main(){
    while(~scanf("%d",&n),n){
        memset(sum,0,sizeof(sum));
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
            b[i]=a[i];
        }
        long long ans=0;
        sort(b,b+n);
        int cnt=unique(b,b+n)-b;
        for(int i=0;i<n;i++){
            int pos=lower_bound(b,b+cnt,a[i])-b;
            pos++;
            ans+=(pos-1-getsum(pos-1));
            update(pos);
        }
        printf("%lld\n",ans);
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值