There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=i<j<=N and A[i]>A[j].
Input
The first line of the input contains the number N. The second line contains N numbers A1...AN.
Output
Write amount of such pairs.
Sample test(s)
Input
5 2 3 1 5 4
Output
3
树状数组求逆序数
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
long long a,b;
}s[66000];
long long c[66000],r[66000];
long long N;
int cmp(node a,node b){
if(a.a!=b.a)
return a.a<b.a;
return a.b<b.b;
}
long long lowbit(long long x){
return x&(-x);
}
void add(long long i,long long x){
while(i<=N)
{
c[i]=c[i]+x;
i+=lowbit(i);
}
}
long long Sum(long long n){
long long sum=0;
while(n>0)
{
sum+=c[n];
n-=lowbit(n);
}
return sum;
}
int main()
{
long long i,j;
while(cin>>N){
for(i=1;i<=N;i++){
cin>>s[i].a;
s[i].b=i;
}
memset(c,0,sizeof(c));
sort(s+1,s+N+1,cmp);
long long ans=0;
for(j=1;j<=N;j++)
r[s[j].b]=j;
for(i=1;i<=N;i++){
add(r[i],1);
ans+=(i-Sum(r[i]));
}
cout<<ans<<endl;
}
return 0;
}