pb_ds

· · 个人记录

头文件:include<bits/extc++.h>

Dev_C++用不了,but noi_linux中的编辑器可以。

当然分开写也是可以的

include <ext/pb_ds/tree_policy.hpp>
include <ext/pb_ds/hash_policy.hpp>
include <ext/pb_ds/trie_policy.hpp>
include <ext/pb_ds/priority_queue.hpp>

Ps:分开写都得另外加上include<ext/pb_ds/assoc_container.hpp>

命名空间:uing namespace __gnu_pbds;

一、平衡树

定义:  

 int -> 类型  

 null_type -> 为映射类型, 低版本为 null_mapped_type  

 less<int>, greater<int> -> 比较器  

 rb_tree_tag、splay_tree_tag、ov_tree_tag -> 选择树的类型  
 Ps: splay、ov 速度较慢,不建议使用  

 tree_order_statistics_node_update -> 结点更新  


操作:  

 insert(x), erase(x) -> 插入、删除  

 order_of_key(x) -> x 的 rank  

 find_by_order(x) -> rank 为 x 的数  

 lower_bound(x) -> 前继 即 >=x 最小的迭代器  

 upper_bound(x) -> 后继 即 > x 最小的迭代器  

 a.join(b) -> b并入a,前提是两颗树的取值范围不相交  

 a.split(v, b) -> key<=v 的属于 a,其他属于 b   

 Ps:
 1. 插入的元素会去重 just like set  
 2. 排名从 0 开始  

例:

 typedef pair<int,int> P;  
 typedef tree<P,null_type,less<P>,rb_tree_tag,tree_order_statistics_node_update> Tree;
 Tree q;
 Tree::iterator it;

于是乎你就可以把普通平衡树A掉

    for(int i=1;i<=n;i++){
        int opt=read(),x=read();
        if(opt==1) q.insert(make_pair(x,i));
        if(opt==2){
            it=q.lower_bound(make_pair(x,0));
            q.erase(it);
        }
        if(opt==3) printf("%d\n", q.order_of_key(make_pair(x,0))+1);
        if(opt==4){
            it=q.find_by_order(x-1);
            printf("%d\n",*it);
        }
        if(opt==5){
            it=--q.lower_bound(make_pair(x,0));
            printf("%d\n",*it);
        }
        if(opt==6){
            it=q.upper_bound(make_pair(x,n));
            printf("%d\n",*it);
        }
    }

二、可并堆和 Tire , Duck 不必用 pb_ds

极简短的左偏树(我没有判重)

#include<cstdio>
inline void swap(int &x,int &y){x^=y^=x^=y;}
const int N=1e5+1;
int n,m;
int dist[N],val[N],rt[N],p[N],ls[N],rs[N];
int find(int x){return rt[x]==x?x:rt[x]=find(rt[x]);}
int merge(int x,int y){
    if(!x||!y) return x+y;
    if(val[y]<val[x]) swap(x,y);
    rs[x]=merge(rs[x],y);
    if(dist[ls[x]]<dist[rs[x]]) swap(ls[x],rs[x]);
    dist[x]=dist[rs[x]]+1;
    return x;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i=-~i){
        scanf("%d",val+i);
        rt[i]=i;
    }
    dist[0]=-1;
    while(m--){
        int opt,x,y;
        scanf("%d",&opt);
        if(opt==1){
            scanf("%d%d",&x,&y);
            if(p[x]||p[y]) continue;
            x=find(x),y=find(y);
            if(x!=y) rt[x]=rt[y]=merge(x,y);
        }
        if(opt==2){
            scanf("%d",&x);
            if(p[x]){printf("-1\n");continue;}
            x=find(x);
            printf("%d\n",val[x]);
            p[x]=1;
            rt[x]=rt[ls[x]]=rt[rs[x]]=merge(ls[x],rs[x]);
            ls[x]=rs[x]=dist[x]=0;
        }
    }
    return 0;
}

更简短的字典树

void insert(){
    int u=0;
    for(int i=1;a[i];i=-~i){
        int v=a[i]-'a';
        if(!trie[u].son[v])
            trie[u].son[v]=++cnt;
        u=trie[u].son[v];
    }
    trie[u].sum++;
}

三、Hash Table 直接用 unordered_map 即可