P1908 逆序对 -- 离散化

本文介绍了一种解决大数据集上逆序对统计问题的方法,通过使用树状数组和离散化技巧,有效地处理了序列中数值过大的挑战。文章详细解释了离散化的实现过程,并提供了一个C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
猫猫TOM和小老鼠JERRY最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。最近,TOM老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中ai>aj且i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。
Update:数据已加强

输入格式
第一行,一个数n,表示序列中有n个数。

第二行n个数,表示给定的序列。序列中每个数字不超过10^9

输出格式
给定序列中逆序对的数目。

  • 求逆序对一下就想到树状数组(具体过程就不赘述);
  • 但是!序列中每个数字不超过10^9让我们很难办呐
  • 数据太大每次插入和查询就会爆掉
  • 参考我们只要每个数的大小顺序,可以用离散化解决
#include <bits/stdc++.h>
#define il inline
#define re register
using namespace std;
typedef long long ll;
const ll maxn = 5e5+10;
ll tree[maxn], rank[maxn];
ll n, ans;
struct node {
	ll id, v;
}e[maxn];
il bool cmp(node x, node y) {
	if(x.v == y.v) return x.id < y.id;
	return x.v < y.v;
}
il void insert(ll x) {
	//cout << x << endl;
	for(; x <= n; x += x&-x) 
		tree[x]++;
	//cout << tree[x] << " " << x << endl;
}
il ll query(ll x) {
	ll res = 0;
	for(; x > 0; x -= x&-x)
		res += tree[x];
	//cout << tree[x] << endl;
	return res;
}
int main() {
	ans = 0;
    scanf("%lld", &n);
    for(re ll i = 1; i <= n; ++i) 
        scanf("%lld", &e[i].v), e[i].id = i;
    sort(e+1, e+1+n, cmp);
    for(re ll i = 1; i <= n; ++i)
        rank[e[i].id] = i;
    for(re ll i = 1; i <= n; ++i) {
        insert(rank[i]);
        //cout << rank[i] << endl;
        //cout << i - query(rank[i]) << endl;
        ans += i - query(rank[i]);
    }
    printf("%lld",ans);
    return 0;
} 
这道题目还可以使用树状数组或线段树来实现,时间复杂度也为 $\mathcal{O}(n\log n)$。这里给出使用树状数组的实现代码。 解题思路: 1. 读入数据; 2. 将原数列离散化,得到一个新的数列 b; 3. 从右往左依次将 b 数列中的元素插入到树状数组中,并计算逆序对数; 4. 输出逆序对数。 代码实现: ```c++ #include <cstdio> #include <cstdlib> #include <algorithm> const int MAXN = 500005; struct Node { int val, id; bool operator<(const Node& other) const { return val < other.val; } } nodes[MAXN]; int n, a[MAXN], b[MAXN], c[MAXN]; long long ans; inline int lowbit(int x) { return x & (-x); } void update(int x, int val) { for (int i = x; i <= n; i += lowbit(i)) { c[i] += val; } } int query(int x) { int res = 0; for (int i = x; i > 0; i -= lowbit(i)) { res += c[i]; } return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); nodes[i] = {a[i], i}; } std::sort(nodes + 1, nodes + n + 1); int cnt = 0; for (int i = 1; i <= n; ++i) { if (i == 1 || nodes[i].val != nodes[i - 1].val) { ++cnt; } b[nodes[i].id] = cnt; } for (int i = n; i >= 1; --i) { ans += query(b[i] - 1); update(b[i], 1); } printf("%lld\n", ans); return 0; } ``` 注意事项: - 在对原数列进行离散化时,需要记录每个元素在原数列中的位置,便于后面计算逆序对数; -树状数组的大小为 $n$,则树状数组中的下标从 $1$ 到 $n$,而不是从 $0$ 到 $n-1$; - 在计算逆序对数时,需要查询离散化后的数列中比当前元素小的元素个数,即查询 $b_i-1$ 位置上的值; - 在插入元素时,需要将离散化后的数列的元素从右往左依次插入树状数组中,而不是从左往右。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值