Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 67410 | Accepted: 25241 |
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
题解:这题是经典的树状数组求逆序数。由于数比较大先离散化再用树状数组求。
用树状数组求逆序数时候初学者可能有些晕乎,而其他某些博客又有些错误或不易理解,这里就来讲解一下。
首先设树状数组要维护的数组是c[ ],先将其初始化为0
对于每个位置i上的数a[i],它原本应该在的位置是u = a[i],那么就让c[u] = 1,那么i之前小于a[i]的数的个数就是sum[u] - 1,
那么i之前大于a[i]的数的个数就是 i - 1 - (sum[u]-1) =i - sum[u]
代码:
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int rem[500005];
int c[500005];
int n;
int Lowbit(int x) // 2^k
{
return x & (-x);
}
void update(int i, int x)//i点增量为x
{
while(i <= n)
{
c[i] += x;
i += Lowbit(i);
}
}
int sum(int x)//区间求和 [1,x]
{
int sum = 0;
while(x > 0)
{
sum += c[x];
x -= Lowbit(x);
}
return sum;
}
struct node
{
int value;
int before;
}a[500005];
int mmp[500005];
bool compare(node x,node y)
{
return x.value < y.value;
}
int main()
{
while(~scanf("%d",&n))
{
long long res = 0;
memset(c,0,sizeof(c));
if(!n)
break;
for(int i = 1; i <= n ; ++i)
{
scanf("%d",&a[i].value);
a[i].before = i;
}
sort(a+1,a+n+1,compare);
/**
这段离散化做别的题时候发现有错误
这题没有重复元素, 而有重复元素时这个就不行了
这是由于sort是快速排序, 而我们知道快速排序不是稳定排序,
可能会改变相同值元素的相对位置, 求逆序数就会出现错误
for(int i = 1; i <= n; ++i)
{
rem[a[i].before] = i;
}
**/
//改成这个了:
int cnt = 1;
for(int i=1;i<=n;i++){
if(i != 1 && a[i].value != a[i-1].value)
cnt++;
rem[a[i].before] = cnt;
}
for(int i = 1; i <= n; ++i)
{
update(rem[i],1);
res += i-sum(rem[i]);
}
cout<<res<<endl;
}
return 0;
}