【YbtOJ 树状数组 - 2】逆序对

逆序对


题目

在这里插入图片描述


输入

第一行为整数 n n n ,表示序列长度

第二行 n n n 个整数,表示给定的序列

输出

输出逆序对总数


输入样例

4
3 2 3 2

输出样例

3

解题思路

我们这题先从左到右枚举,来计算 a i a_i ai的逆序对,但是这样时间复杂度为 O ( N 2 ) O(N^2) O(N2)

显然不太优,那么我们就可以考虑用树状数组来进行优化,我们依旧先从左到右枚举

每次在树状数组中下标 a i a_i ai的位置加一,查询树状数组中下标大于 a i a_i ai的区间的元素个数,然后进行累计答案即可


程序如下

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;

int n, tot;

long long ans, a[500006], p[500006], c[500006];

void update(int x,int y)
{
	for(; x <= tot; x += x & -x) c[x] += y;
}

long long query(int x)
{
	long long anss = 0;
	for(; x; x -= x & -x) anss += c[x];
	return anss;
}

int main()
{
	scanf("%d",&n);
	for(int i = 1; i <= n; ++i)
	{
		scanf("%lld",&a[i]);
		p[i] = a[i];
	}
	sort(p + 1, p + 1 + n);
	tot = unique(p + 1, p + 1 + n) - 1 - p;
	for(int i = 1; i <= n; ++i)	
		a[i] = lower_bound(p + 1, p + 1 + tot, a[i]) - p;
	for(int i = 1; i <= n; ++i)
	{
		update(a[i], 1);
		ans += query(tot) - query(a[i]);
	}
	printf("%lld",ans);
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值