背景
听说 pb_ds 可以代替简单的平衡树,所以学习了一下其中 tree 的使用。
参考了 oi-wiki 和于纪平的课件《C++ 的 pb_ds 库在 OI 中的应用》。
pb_ds 简介
pb_ds(Policy-Based Data Structures)是可以在竞赛活动中使用的,官方允许使用的文件。
pb_ds 的万能头文件:
#include<bits/extc++.h>如果 TDM-GCC 过不了编译,可以在引用万能头文件前取消一个宏定义:
#undef _GLIBCXX_HAVE_ICONV
#include<bits/extc++.h>这样就可以使用了。
pb_ds 有专门的命名空间:
using namespace __gnu_pbds;tree 的使用方法
tree 的模板形参:
tree<Key,Mapped,Cmp_Fn=less<Key>,Tag=rb_tree_tag,Node_Update=null_tree_node_update,Allocator=allocator<char>>参数的含义:
Key是数据类型。我们这里为了储存多个相同值的元素,可以用pair<int,int>。Mapped是映射规则:如果要用类似set的数据结构,就填null_type,用类似map的数据结构对应类型为Value的值,填map<Key,Value>。本题填null_type即可。Cmp_Fn是比较规则,本题从小到大就是less<pair<int,int>>。Tag是平衡树的种类,有红黑树:rb_tree_tag、神秘数据结构 $p14y 7r33 7481:splay_tree_tag、有序向量树(复杂度高):ov_tree_tag。一般用红黑树最快。Node_Update是维护节点的类型,如果要查排名就设为tree_order_statistics_node_update。可以按需要自定义。
常用的成员函数(和 map、set 差不多):
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。
要查排名的话,会多两个函数:
iterator find_by_order(size_type order);
size_type order_of_key(key_const_reference r_key);这两个函数分别用于找第 order+1 小的元素迭代器和查询有多少个小于 r_key 的元素。
本题做法
存入值和当前操作次数的 pair,然后按定义使用上面的函数模拟。
可以练习一下这些函数的使用。
实现
#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;
}