Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 56422 | Accepted: 20845 |
Description
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
Output
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;
}