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
题解:离散化之后树状数组统计求和即可。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define _for(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
const int maxn = 70000;
struct node
{
int id,num;
bool operator<(const node& a)const
{
return num<a.num;
}
}a[maxn];
int n,b[maxn];
ll c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
while(x<=n)
{
c[x]++;
x+=lowbit(x);
}
}
ll sum(int x)
{
ll now = 0;
while(x>0)
{
now+=c[x];
x-=lowbit(x);
}
return now;
}
int main(int argc, char const *argv[])
{
cin>>n;
_for(i,1,n)
{
cin>>a[i].num;
a[i].id=i;
}
sort(a+1,a+1+n);
b[a[1].id]=1;
_for(i,2,n)
{
if(a[i].num!=a[i-1].num)b[a[i].id]=i;
else b[a[i].id]=b[a[i-1].id];
}
ll ans = 0;
_for(i,1,n)
{
update(b[i]);
ans+=sum(n)-sum(b[i]);
}
cout<<ans<<endl;
return 0;
}