树状数组
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 500005
struct Elem
{
int p, v;
}s[maxn];
int f[maxn];
int pos[maxn];
int ar[maxn];
bool operator < (const Elem &a, const Elem &b)
{
return a.v < b.v;
}
int lowb(int t)
{
return t & (-t);
}
void add(int i, int v)
{
for (; i < maxn; ar[i] +=v, i += lowb(i));
}
int sum(int i)
{
int s = 0;
for (; i > 0; s += ar[i], i -= lowb(i));
return s;
}
int main()
{
//freopen("t.txt", "r", stdin);
int n;
memset(ar, 0, sizeof(ar));
while (scanf("%d", &n), n)
{
memset(ar, 0, sizeof(ar));
for (int i = 0; i < n; i++)
{
scanf("%d", &f[i]);
s[i].v = f[i];
s[i].p = i;
}
sort(s, s + n);
for (int i = 0; i < n; i++)
pos[s[i].p] = i + 1;
long long ans = 0;
for (int i = n - 1; i >= 0; i--)
{
ans += sum(pos[i] - 1);
add(pos[i], 1);
}
printf("%lld\n", ans);
}
return 0;
}