浅谈 rope

前言

今天做了 UVA12538 自带版本控制功能的IDE Version Controlled IDE 看了下题解发现可以用 rope 直接水过,所以发篇博客,记录一下 rope 的用法。

简介

rope 的本质就是块状链表。rope 是 C++ STL 中 pbds 的一个分支,想要引用,需要加上两行代码:

1
2
#include <ext/rope>
using namespace __gnu_cxx;

rope 可以实现在 $\mathcal O(1)$ 的时间拷贝历史版本,所以其可以轻松实现可持久化。

定义

1
crope a,b;

操作

首先定义一个 crope a;

  • a.push_back(x):在 a 的末尾添加 x
  • a.insert(p,x): 在 a 的位置 p 后面添加 x
  • a.erase(p,x): 从 a 的位置 p 开始删除 x 个元素。
  • a.replace(p,x): 从 a 的位置 p 开始换成 x
  • a.substr(p,x):从 a 的位置 p 开始截取 x 个元素。
  • a.at(x):访问 a 的第 x 个元素。(其实第五种操作可以替代这个操作)

然后如果有 $n$ 个操作,时间复杂度是 $\mathcal O(N^{1.5})$

例题

然后你就可以秒了这道黑题了:UVA12538 自带版本控制功能的IDE Version Controlled IDE

当然你也可以写块链,再套上个可持久化的话就得再套个分块,反正我是懒得写。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define W while
#define I inline
#define RI register int
#define LL long long
#define Cn const
#define CI Cn int&
#define gc getchar
#define D isdigit(c=gc())
#define pc(c) putchar((c))
#include <ext/rope>
using namespace __gnu_cxx;
using namespace std;
namespace Debug{
Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;}
Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;}
#define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
namespace FastIO{
Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;}
Ts I void read(Ty& x,Ar&... y){read(x),read(y...);}
Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'),0);}
Tp I void writeln(Cn Ty& x){write(x),pc('\n');}
}using namespace FastIO;
Cn int N=5e4+10;
int m,L;
char str[N];
crope nw,s[N],t;
int main(){
RI b=0,opt,p,v,c;read(m);W(m--) if(read(opt),opt==1) read(p),scanf("%s",&str),p-=b,nw.insert(p,str),s[++L]=nw;
else if(opt==2) read(p,v),p-=b,v-=b,nw.erase(p-1,v),s[++L]=nw;
else read(v,p,c),v-=b,p-=b,c-=b,t=s[v].substr(p-1,c),b+=count(t.begin(),t.end(),'c'),cout<<t<<'\n';return 0;
}