树状数组主要两个操作,求和,修改
#include<iostream>
#include<algorithm>
using namespace std;
#define N 500001
int c[N];
int n;
struct Node
{
int val;
int pos;
};
Node node[N];
int a[N];
int lowbit(int x)
{
return x&(-x);
}
int sum(int i)
{
int s = 0;
while (i > 0)
{
s += c[i];
i -= lowbit(i);
}
return s;
}
void add(int i, int val)
{
while (i <= n)
{
c[i] += val;
i+= lowbit(i);
}
}
int cmp(const void *a, const void *b)
{
return (((Node*)a)->val) - (((Node*)b)->val);
}
int main()
{
while (cin >> n, n)
{
for (int i = 1; i <= n; i++)
{
cin >> node[i].val;
node[i].pos = i;
}
qsort(node+1, n, sizeof(Node), cmp);
for (int i = 1; i <=n; i++)
a[node[i].pos] = i;
long long ans=0;//注意数据范围
//for (int i = 1; i <= n; i++)
//cout<<node[i].val<<ends;
for (int i = 1; i <= n; i++)
c[i] = 0;
for (int i = 1; i <=n; i++)
{
add(a[i], 1);
ans += (i - sum(a[i]));
}
cout << ans << endl;
}
}