跳到正文

题解

P1908 逆序对题解

zhengyi0402约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月5日
收录
2025年12月12日
更新
2026年11月12日
篇幅
约 5 分钟
题目
P1908

版本

  1. v1当前

P1908 逆序对题解

观前提示

  1. 此方法并非传统方法,需要吸氧。
  2. 此方法需要在高版本的 C++ 中运行。

数据范围

1≤n≤5×1051 \le n \le 5 \times 10 ^ 5

1≤ai≤1091 \le a_i \le 10^9

二十五分思路

可以使用 multiset。

由于 multiset 中的元素是有序的,我们可以定位到第一个小于 aia_i 的位置。

这有什么用呢?

因为前面的数一个比一个小,所以其位置就是答案。

最后用 ansans 将所有答案之和记录即可。

但是,由于查找位置的函数时间复杂度过高(最高 O(n)O(n)),所以该方法只能得二十五分。

二十五分代码

C++
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define atn 222222
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define f(i,a,b) for(int i = a;i <= b;++i)
#define ff(i,a,b) for(int i = a;i >= b;--i)
using namespace std;
int a[555555];
multiset<int> s;
signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	int n;
	cin>>n;
	f(i,1,n)cin>>a[i];
	int ans = 0;
	s.insert(a[n]);
	ff(i,n-1,1){
		int tt = 0;
		auto it = s.lower_bound(a[i]);
		tt = distance(s.begin(),it);
		ans+=tt;
		s.insert(a[i]);
	} 
	cout<<ans;
	return 0;
	//十年OI一场空,define int 见祖宗。
	//十年OI一场空,不开long long见祖宗。
}

满分思路

在查找大量资料后,我发现了一种 O(log⁡n)O(\log n) 的稳定查询方法。

这种方法需要将 multiset 改为 indexed_multiset。

然后,在代码中加上下面的片段:

C++
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<typename T>
using indexed_multiset = tree<
    T, null_type, std::less_equal<T>,
    rb_tree_tag, tree_order_statistics_node_update>;

这样,就可以用 order_of_key 函数查找每个位置了。

大体思路还是跟二十五分做法相同。

代码

C++
#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define atn 222222
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define f(i,a,b) for(ll i = a;i <= b;++i)
#define ff(i,a,b) for(ll i = a;i >= b;--i)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<typename T>
using indexed_multiset = tree<
    T, null_type, std::less_equal<T>,
    rb_tree_tag, tree_order_statistics_node_update>;
ll a[555555];
indexed_multiset<ll> s;
signed main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	ll n;
	cin>>n;
	f(i,1,n)cin>>a[i];
	ll ans = 0;
	s.insert(a[n]);
	ff(i,n-1,1){
		ll tt = 0; 
		tt = s.order_of_key(a[i]);
		ans+=tt;
		s.insert(a[i]);
	} 
	cout<<ans;
	return 0;
	//十年OI一场空,define int 见祖宗。
	//十年OI一场空,不开long long见祖宗。
}
原文