Description
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
Input
5 2 3 1 5 4
Output
3
仍然是逆序数。不知道哪个oj上的
要用__int64,不能用long long
离散化的时候要注意相同的值
还有注意从后往前插,查询比其小的数字的个数
不需要多组数据。(tle n次)
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=65540;
int a[maxn];
int c[maxn];
struct Item
{
int val;
int pos;
}item[maxn];
bool cmp(Item a,Item b)
{
return a.val<b.val;
}
int n;
int Lowbit(int x)
{
return x&(-x);
}
void update(int x,__int64 val)
{
for(int i=x;i<n;i+=Lowbit(i))
a[i]+=val;
}
__int64 query(int x)
{
__int64 ans=0;
for(int i=x;i>0;i-=Lowbit(i))
ans+=a[i];
return ans;
}
int main()
{
__int64 ans=0;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&item[i].val);
item[i].pos=i;
}
sort(item+1,item+n+1,cmp);
c[item[1].pos]=1;
for(int i=2;i<=n;i++){
if(item[i].val!=item[i-1].val)
c[item[i].pos]=i;
else
c[item[i].pos]=c[item[i-1].pos];
}
for(int i=n;i>=1;i--){
update(c[i],1);
ans+=query(c[i]-1);
}
printf("%I64d\n",ans);
return 0;
}