题目链接https://www.luogu.org/problem/P1908
题目描述
猫猫TOM和小老鼠JERRY最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。最近,TOM老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中ai>aj且i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。
Update:数据已加强。
输入格式
第一行,一个数n,表示序列中有n个数。
第二行n个数,表示给定的序列。序列中每个数字不超过10^9109
输出格式
给定序列中逆序对的数目。
输入输出样例
输入
6
5 4 2 6 3 1
输出
11
说明/提示
对于25%的数据,n≤2500
对于50%的数据,n≤4×10^4。
对于所有数据,n≤5×10^5
请使用较快的输入输出
应该不会n方过50万吧 by chen_zhe
这题有很多种方法,离散化线段树、树状数组或者归并排序
这里给出归并排序写法的链接:归并排序写法链接https://blog.csdn.net/qq_43906000/article/details/100588126
离散化线段树的话,写起来比较复杂,特别是区间离散化的时候就有点麻烦,需要隔板之类的,代码量比较大,但动态开点线段树的话写起来就非常简洁了,不容易出错。
我们一般的线段树的左右儿子是rt2和rt2+1,但动态开点的话就是由动态分配编号而来的,所以我们需要记录它的左儿子后右儿子的编号,接下来的操作就是和普通的线段树差不多了,代码中会有注释。
AC代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define lson l,mid,tree[rt].l
#define rson mid+1,r,tree[rt].r
#define ls tree[rt].l
#define rs tree[rt].r
const int mac=5e5+10;
const int inf=1e9+5;
struct node
{
int l,r,sum;
}tree[mac*32];
int sz=1;//动态分配的点的最大编号
ll query(int l,int r,int rt,int L,int R)
{
ll ans=0;
if (l>=L && r<=R){
return tree[rt].sum;
}
int mid=(l+r)>>1;
if (mid>=L) ans+=query(lson,L,R);
if (mid<R) ans+=query(rson,L,R);
return ans;
}
void update(int l,int r,int &rt,int pos)
{
if (!rt) rt = ++sz;//如果说这个节点不存在,我们就将节点数+1,当前节点为最大最大节点,和主席树有点类似,而这也是动态开点的核心
if (l==r) {
tree[rt].sum++;
return;
}
int mid=(l+r)>>1;
if (mid>=pos) update(lson,pos);//注意这里传进去的rt是左儿子的编号
else update(rson,pos);
tree[rt].sum=tree[ls].sum+tree[rs].sum;
}
int main()
{
int n;
scanf ("%d",&n);
ll ans=0;
int root=1;
for (int i=1; i<=n; i++){
int x;
scanf ("%d",&x);
ans+=query(1,inf,1,x+1,inf);
update(1,inf,root,x);
}
printf ("%lld\n",ans);
return 0;
}