题目描述
猫猫 TOM 和小老鼠 JERRY 最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。
最近,TOM 老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中 a_i>a_jai>aj 且 i<ji<j 的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。注意序列中可能有重复数字。
Update:数据已加强。
输入格式
第一行,一个数 nn,表示序列中有 nn个数。
第二行 nn 个数,表示给定的序列。序列中每个数字不超过 10^9109。
输出格式
输出序列中逆序对的数目。
输入输出样例
输入 #1复制
6 5 4 2 6 3 1
输出 #1复制
11
说明/提示
对于 25\%25% 的数据,n \leq 2500n≤2500
对于 50\%50% 的数据,n \leq 4 \times 10^4n≤4×104。
对于所有数据,n \leq 5 \times 10^5n≤5×105
请使用较快的输入输出
应该不会 O(n^2)O(n2) 过 50 万吧 by chen_zhe
树状数组求逆序对的过程用模拟好理解一些。是用树状数组维护一个桶,在for中扫一遍的过程就是i<j的过程,在桶中log(N)维护前缀和
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
#define lowbit x&(-x);
using namespace std;
const int maxn=5e5+10;
typedef long long LL;
LL tree[maxn];
LL n;
struct P{
LL val,index;
}a[maxn];
bool cmp(P A,P B){
if(A.val==B.val) return A.index<B.index;
return A.val<B.val;
}
LL add(LL x,LL d){
while(x<=n){
tree[x]+=d;
x+=lowbit(x);
}
}
LL sum(LL x){
LL sum=0;
while(x>0){
sum+=tree[x];
x-=lowbit(x);
}
return sum;
}
int main(void)
{
cin.tie(0);std::ios::sync_with_stdio(false);
cin>>n;
for(LL i=1;i<=n;i++){
cin>>a[i].val;a[i].index=i;
}
sort(a+1,a+1+n,cmp);
LL ans=0;
for(LL i=1;i<=n;i++){
add(a[i].index,1);
ans+=i-sum(a[i].index);
}
cout<<ans<<endl;
return 0;
}