基本的樹狀數組求逆序對
// Ultra-QuickSort
// http://poj.org/problem?id=2299
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define forloop(i, a, b) for(int i = a; i < b; i++)
#define fordown(i, a, b) for(int i = a; i > b; i--)
using namespace std;
const int maxn = 500010;
typedef long long LL;
struct Node {
int val, id;
};
int n;
Node a[maxn];
int arr[maxn];
inline int lowbit(int x) {
return x & -x;
}
void add(int x, int v) {
for (int i = x; i < n + 4; i += lowbit(i)) {
arr[i] += v;
}
}
LL sum(int x) {
LL s = 0;
for (int i = x; i ; i -= lowbit(i)) {
s += arr[i];
}
return s;
}
struct NodeCmp {
bool operator() (const Node& l, const Node& r) {
return l.val < r.val;
}
};
int main() {
while (cin >> n) {
if (n == 0) break;
memset(arr, 0, sizeof(int) * (n + 10));
forloop(i, 1, n+1) {
scanf("%d", &a[i].val);
a[i].id = i;
}
sort(a+1, a+1+n, NodeCmp());
LL ans = 0;
fordown(i, n, 0) {
ans += sum(a[i].id - 1);
add(a[i].id, 1);
}
cout << ans << endl;
}
return 0;
}