题解 P3369 【【模板】普通平衡树(Treap/SBT)】

· · 题解

STL真是个好东西。

最近在看pb_ds库及vector和set的用法,就想用这三种操作来实现一下普通平衡树,结果pb_ds中的rbtree不支持重复值,而本蒟蒻也看不懂不懂各大佬用pb_ds的实现,况且应该有人已经贴上了题解。我就发一发vector和set(其实是multiset)的题解吧。(只不过蒟蒻的我我根本不会打splay)

代码都很短,操作其实也很基础。

vector版:

开O2跑得比香港记者还快,不开O2好像最慢的300多ms

set版:

C++ STL中的set好像是用红黑树实现的,但是它并不支持重复元素,所以我们只能用multiset,然而用multiset(其实set也是)搞排名之类的就好复杂了......看网上说好像是STL中的红黑树并没有维护什么size域,我也不太懂。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <set>
#include <cctype>
using namespace std;
multiset <int>a;
int read()
{
    int x=0;char ch;short int neg=0;ch=getchar();
    while(!isdigit(ch)){
        neg|=(ch=='-');ch=getchar();
    }
    while(isdigit(ch)){
        x=x*10+ch-48;ch=getchar();
    }
    return neg?-x:x;
}
int main()
{
    int n,op;
    cin>>n;
    while(n--)
    {
        cin>>op;
        register int x=read();
      if(op==1)a.insert(upper_bound(a.begin(),a.end(),x),x);
      else if(op==2)a.erase(lower_bound(a.begin(),a.end(),x));
      else if(op==3)cout<<distance(a.begin(),a.upper_bound(x))<<endl;
      else if(op==4)
              {multiset<int>::iterator it =a.begin();
               //int k=distance(a.begin(),a+x);
               advance(it,x-1); cout<<' '<<*it<<endl;}
      else if(op==5) cout<<*--lower_bound(a.begin(),a.end(),x)<<endl;
      else { pair<multiset<int>::const_iterator,multiset<int>::const_iterator> it;
               it=a.equal_range(x);cout<<*it.second<<endl;}//cout<<*upper_bound(a.begin(),a.end(),x)<<endl;   
    }
    return 0;
}

当然,STL不会支持更多变式操作况且现在裸题也越来越少,但它用来优化某些东西或是对拍还是非常有用的。

本蒟蒻也要开始学splay了