Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 56422 | Accepted: 20845 |
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.
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
a[i]的数据范围太大,直接存树状数组存不开,要离散化一下。因为题目中说明了a中每个数字是唯一的,所以可以对a中的数重新赋一个新的较小值,并且不改变他们的相对大小,这样数据范围就可以减小到n了,再用树状数组求逆序数就行了
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
typedef long long ll;
struct node {
int num, i;
node() {}
node(int i, int num) : i(i), num(num) {}
bool operator < (const node& on) const {
return this->num < on.num;
}
}s[500005];
int n, cnt;
int a[500005], BIT[500005];
int lowbit(int x) {
return x & (-x);
}
void add(int x, int y) {
for (int i = x; i <= cnt; i += lowbit(i)) {
BIT[i] += y;
}
}
int sum(int x) {
int res = 0;
for (int i = x; i > 0; i -= lowbit(i)) {
res += BIT[i];
}
return res;
}
int Sum(int l, int r) {
return sum(r) - sum(l - 1);
}
int main()
{
while (~scanf("%d", &n) && n) {
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
s[i] = node(i, a[i]);
}
sort(s + 1, s + 1 + n);
cnt = 0;
for (int i = 1; i <= n; i++) {
a[s[i].i] = ++cnt;
}
ll ans = 0;
memset(BIT, 0, sizeof(BIT));
for (int i = 1; i <= n; i++) {
add(a[i], 1);
ans += Sum(a[i] + 1, cnt);
}
printf("%lld\n", ans);
}
return 0;
}