http://poj.org/problem?id=2299
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=1000010;
int n,c[maxn];
int lowbit(int x)
{
return x&(-x);
}
ll query(int x)
{
ll res=0;
while(x)
{
res+=c[x];
x-=lowbit(x);
}
return res;
}
void add(int x,int val)
{
while(x<=n)
{
c[x]+=val;
x+=lowbit(x);
}
}
struct node
{
int val,id;
};
bool cmp(node a,node b)
{
return a.val<b.val;
}
node a[maxn];
int b[maxn];
int main()
{
//int x,y;
while(scanf("%d",&n))
{
if(n==0)
break;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].val);
a[i].id=i;
}
sort(a+1,a+1+n,cmp);
int f=1;
b[a[1].id]=1;
for(int i=2;i<=n;i++)
{
if(a[i].val==a[i-1].val)
{
b[a[i].id]=b[a[i-1].id];
}
else
{
b[a[i].id]=++f;
}
}
ll ans=0;
memset(c,0,sizeof(c));
for(int i=n;i>=1;i--)
{
add(b[i],1);
ans+=query(b[i]-1);
}
printf("%lld\n",ans);
}
}