1019 逆序数
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 取消关注
在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。
Input
第1行:N,N为序列的长度(n <= 50000)
第2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9)
Output
输出逆序数
Input示例
4
2
4
3
1
Output示例
4
思路:简单的树状数组应用
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
const int MAXN = 50005*4;
int n;
//树状数组一般有n个节点
int C[MAXN];
int lowbit(int x)
{
return x & -x;
}
int sum(int x)
{
int ret = 0;
while(x > 0)
{
ret += C[x];
x -= lowbit(x);
}
return ret;
}
int add(int x,int d)
{
while(x <= n)
{
C[x] += d;
x += lowbit(x);
}
}
struct p{
int value;
int index;
bool operator >(const p& pp)const{
return value>pp.value;
}
bool operator <(const p& pp)const{
return value<pp.value;
}
bool operator ==(const p& pp)const{
return value==pp.value;
}
};
p a[50005];
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i].value;
a[i].index=i+1;
}
sort(a,a+n);
long long res=0;
int cns=1;
for(int i=n-1;i>=0;i--){
//cout<<a[i].value<<"--"<<endl;
add(a[i].index,1);
res+=sum(a[i].index)-1;
}
cout<<res<<endl;
return 0;
}