G Iversions
G. Inversions
Time Limit: 500ms
Case Time Limit: 500ms
Memory Limit: 4096KB
64-bit integer IO format: %I64d Java class name: Solution
Font Size:
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 Input
Sample test(s)
Input
5
2 3 1 5 4
2 3 1 5 4
Output
3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <algorithm>
using namespace std;
struct node
{
int origin;
int set;
}a[65539],b[65539];
int n;
int c[65539],sa[65539];
bool cmp(const node &aa,const node &bb)
{
return aa.origin<bb.origin;
}
bool cmps(const node &aa,const node &bb)
{
return aa.set<bb.set;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int i,int x)
{
while(i<=n)
{
c[i]+=x;
i+=lowbit(i);
}
}
int getsum(int i)
{
int sum=0;
while(i>0)
{
sum+=c[i];
i-=lowbit(i);
}
return sum;
}
int main()
{
int i,k;
__int64 ss;
while(scanf("%d",&n)!=EOF)
{
ss=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i].origin);
a[i].set=i;
}
sort(a+1,a+n+1,cmp);
k=1;
a[0].origin=-1;
for(i=1;i<=n;i++) //注意离散化的时候考虑相等的情况
{
if(a[i].origin==a[i-1].origin)
{
b[i].origin=b[i-1].origin;
b[i].set=a[i].set;
}
else
{
b[i].origin=k++;
b[i].set=a[i].set;
}
}
sort(b+1,b+n+1,cmps);
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
{
update(b[i].origin,1);
ss=ss+i-getsum(b[i].origin);
}
printf("%I64d\n",ss);
}
}