跳到正文

题解

pb_ds tree

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

文章信息

收录
2025年12月12日
更新
2026年4月13日
篇幅
约 5 分钟
题目
P6136

版本

  1. v1当前

背景

听说 pb_ds 可以代替简单的平衡树,所以学习了一下其中 tree 的使用。

参考了 oi-wiki 和于纪平的课件《C++ 的 pb_ds 库在 OI 中的应用》。

pb_ds 简介

pb_ds(Policy-Based Data Structures)是可以在竞赛活动中使用的,官方允许使用的文件。

pb_ds 的万能头文件:

C++
#include<bits/extc++.h>

如果 TDM-GCC 过不了编译,可以在引用万能头文件前取消一个宏定义:

C++
#undef _GLIBCXX_HAVE_ICONV
#include<bits/extc++.h>

这样就可以使用了。

pb_ds 有专门的命名空间:

C++
using namespace __gnu_pbds;

tree 的使用方法

tree 的模板形参:

C++
tree<Key,Mapped,Cmp_Fn=less<Key>,Tag=rb_tree_tag,Node_Update=null_tree_node_update,Allocator=allocator<char>>

参数的含义:

  1. Key 是数据类型。我们这里为了储存多个相同值的元素,可以用 pair<int,int>。
  2. Mapped 是映射规则:如果要用类似 set 的数据结构,就填 null_type,用类似 map 的数据结构对应类型为 Value 的值,填 map<Key,Value>。本题填 null_type 即可。
  3. Cmp_Fn 是比较规则,本题从小到大就是 less<pair<int,int>>。
  4. Tag 是平衡树的种类,有红黑树:rb_tree_tag、神秘数据结构 $p14y 7r33 7481:splay_tree_tag、有序向量树(复杂度高):ov_tree_tag。一般用红黑树最快。
  5. Node_Update 是维护节点的类型,如果要查排名就设为 tree_order_statistics_node_update。可以按需要自定义。

常用的成员函数(和 map、set 差不多):

C++
begin();
end();
size();
empty();
clear();
find(const Key);
lower_bound(const Key);
upper_bound(const Key);
erase(iterator);
erase(const Key);
insert(const pair<Key,T>);
void join(tree &other);
void split(const_key_reference r_key,tree &other);

上述最后两个函数分别把树 other 合并到当前树(值域不交)和用当前树上所有大于 r_key 的元素覆盖 other。

要查排名的话,会多两个函数:

C++
iterator find_by_order(size_type order);
size_type order_of_key(key_const_reference r_key);

这两个函数分别用于找第 order+1 小的元素迭代器和查询有多少个小于 r_key 的元素。

本题做法

存入值和当前操作次数的 pair,然后按定义使用上面的函数模拟。

可以练习一下这些函数的使用。

实现

C++
#include<bits/stdc++.h>
#include<bits/extc++.h>
using namespace std;
using namespace __gnu_pbds;
tree<pair<int,int>,null_type,less<pair<int,int>>,rb_tree_tag,tree_order_statistics_node_update> tr;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n,m;
	cin>>n>>m;
	for(int i = 1,x; i <= n; i ++) cin>>x,tr.insert({x,i});
	int ans = 0;
	for(int i = n + 1,res = 0; i <= n + m; i ++)
	{
		int x,y;
		cin>>x>>y;
		y ^= res;
		if(x == 1) tr.insert({y,i});
		else if(x == 2) tr.erase(tr.lower_bound({y,0}));
		else if(x == 3) res = tr.order_of_key({y,0}) + 1,ans ^= res;
		else if(x == 4) res = (*tr.find_by_order(y - 1)).first,ans ^= res;
		else if(x == 5) res = (* -- tr.lower_bound({y,0})).first,ans ^= res;
		else res = (*tr.upper_bound({y,1e9})).first,ans ^= res;
	}
	cout<<ans<<endl;
	return 0;
}
原文