Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 62722 | Accepted: 23367 |
Description
![](https://i-blog.csdnimg.cn/blog_migrate/b3530eaa8fa98ef394d3639722240a8c.jpeg)
Ultra-QuickSort produces the output
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;
}