# Ultra-QuickSort

9 1 0 5 4 ,

Ultra-QuickSort produces the output
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
using namespace std;

__int64 ans;
int num[500010];
int bit[500010];
pair<int,int> ps[500010];
int n;

{
while(x<=n){
bit[x]+=1;
x+=x&-x;
}
}

__int64 countn(int x)
{
__int64 an=0;
while(x){
an+=bit[x];
x-=x&-x;
}
return an;
}

int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%d",&n)&&n)
{
memset(bit,0,sizeof bit);
ans=0;
for(int i=1;i<=n;i++){
cin>>ps[i].first;
ps[i].second=i;
}
sort(ps+1,ps+n+1);
num[ps[1].second]=1;
for(int i=2;i<=n;i++){
if(ps[i].second==ps[i-1].second)
num[ps[i].second]=num[ps[i-1].second];
else
num[ps[i].second]=i;
}
for(int i=1;i<=n;i++){
ans+=countn(n)-countn(num[i]);
}