跳到正文

算法·理论

P1908 逆序对(树状数组) 讲解

mairuisheng约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年4月18日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

P1908 逆序对(树状数组) 讲解

  • 题目:P1908 逆序对

  • 题意:求 aa 数列中 ai>aja_i>a_j 且 i<ji<j 的数量.

  • 解题思路:

  1. 离散化:

    将原始数组映射到 1∼n1\sim n 的连续整数,解决数值过大导致的树状数组空间浪费问题。

  2. 逆序遍历统计:

    从后向前遍历数组,每次操作:

    查询前缀和:统计已插入元素中小于当前元素的数量。

    插入当前元素:将当前元素位置标记为已出现。

    总逆序对=∑(当前遍历时已插入元素总数−已插入元素中小于当前元素的数量)总逆序对=\sum(当前遍历时已插入元素总数-已插入元素中小于当前元素的数量)

  3. 树状数组操作:

    单点更新:插入元素时,将对应位置值 +1+1。

    前缀和查询:查询当前元素左侧已插入元素的数量。

  4. 其他:

    需要倒序排序。

    时间复杂度:O(nlog⁡n)O(n\log n)

  • 参考代码:
C++
//#pragma GCC optimize(3)
#include<cstdio>
#include<algorithm>
#define int long long//数据范围大,记得开 long long
using namespace std;
inline int read()//快读
{
	int x=0,f=1;
	char s;
	s=getchar();
	while(s<48||s>57)
	{
		if(s=='-')f=-f;
		s=getchar();
	}
	while(s>47&&s<58)
	{
		x=(x<<3)+(x<<1)+(s-48);
		s=getchar();
	}
	return x*f;
}
const int N=5e5+1;
struct Node
{
	int val;
	int pos;
}a[N];//保存数列 a 的数值和位置
bool cmp(Node x,Node y)//逆序对:倒序排序
{
	if(x.val==y.val)return x.pos>y.pos;
	return x.val>y.val;
}
int n;
int ans;//答案
int sum[N];//树状数组
int lowbit(int x)//获取整数二进制表示中最低位的1及其后所有0组成的数值
{
	return x&-x;
}
void update(int x,int k)//更新
{
	for(;x<=n;x+=lowbit(x))sum[x]+=k;
}
int query(int x)//查询
{
	int res=0;
	for(;x;x-=lowbit(x))res+=sum[x];
	return res;
}
signed main()
{
	n=read();
	int i;
	for(i=1;i<=n;++i)
	{
		a[i].val=read();//数值
		a[i].pos=i;//下标
	}
	sort(a+1,a+1+n,cmp);//离散化
	for(i=1;i<=n;++i)
	{
		ans+=query(a[i].pos-1);//查询
		update(a[i].pos,1);//更新
	}
	printf("%lld",ans);
	return 0;
}
原文