C++ pbds 库平衡树(tree)

头文件

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//或者直接用
#include <bits/extc++.h>

命名空间

using namespace __gnu_pbds;

定义

tree<double, null_type, greater<double>, rb_tree_tag, tree_order_statistics_node_update> T;
//这个东西有一点点长
//第一个参数是数据类型
//第二个要填null_type,低版本编译器填null_mapped_type
//第三个填比较函数 std::greater<> or std::less<> or cmp
//第四个填树的类型,有rb_tree_tag红黑树和splay_tree_tag
//第五个是为了支持查询第k大和排名的一个参数
//tree_order_statistics_node_update

使用

这个东西和(set)一样不支持重复元素,所以一般用(double),或者自定义结构体变量或者用(pair)都是可以的,只要记住千万不要插入重复元素就好了。

洛谷模板:普通平衡树

#include <cstdio>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>

using namespace std;
using namespace __gnu_pbds;

tree<double, null_mapped_type, greater<double>, rb_tree_tag, tree_order_statistics_node_update> T;

int main()
{
	//freopen("3369.in", "r", stdin);
	//freopen("3369.out", "w", stdout);

	int q, opt, x;

	scanf("%d", &q);
	for (int i = 1; i <= q; ++ i)
	{
		scanf("%d%d", &opt, &x);
		if(opt == 1) 
			T.insert(x + i * 1e-6);
		//插入一个数
		if(opt == 2) 
			T.erase(T.lower_bound(x));
		//删除一个数
		if(opt == 3) 
			printf("%dn", (int)T.order_of_key(x) + 1);
		//查询一个数的排名
		if(opt == 4) 
			printf("%dn", (int)*T.find_by_order(x - 1));
		//查询第k小的数 返回的是一个迭代器 这里k是从0开始算的,意思是最小的数是第0小的
		if(opt == 5) 
			printf("%dn", (int)round(*(-- T.lower_bound(x))));
		//查询一个数的前驱
		if(opt == 6) 
			printf("%dn", (int)round(*T.lower_bound(x + 1)));
		//查询一个数的后继
	}

	return 0;
}

这个东西在比赛中是可以用的,所以如果嫌打平衡树太麻烦就可以直接用啦。

在这里插入图片描述

原文链接: https://www.cnblogs.com/brunch/p/9929832.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ pbds 库平衡树(tree)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/284561

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(1)
上一篇 2023年2月15日 上午8:00
下一篇 2023年2月15日 上午8:01

相关推荐