题目链接
题解:
今天准备写Splay题目的时候,搜到了这个题,却发现了一个新玩意儿(rope
必需的头文件
#include<ext/rope>
using namespace __gnu_cxx;
rope 不属于标准 STL,属于扩展 STL,来自 pb_ds 库,可以做到O(1)复制原来的数组,但事实上rope的内置实现也是一个平衡树,由于只需要复制根节点,所以可以O(1)做到复制历史版本,可惜的是这个东西常数特别大,不开O2容易被卡
rope支持的操作(以这道题的char为例):
insert(int pos,char *s,int n):把字符串s的前n位插入到rope的下标pos处后,如果没有n,则全部插入到pos处
append(char *s,int pos,int n):把字符串s的pos到n位插入到rope的最后
substr(int pos,int len):提取rope中从pos开始的len个字符
at(int x):访问rope小标为x的元素
erase(int pos,int len):删除rope中从pos开始的len个字符
copy(int pos,int len,char *s):从rope下标为pos开始的len位复制用s代替
时间复杂度:O(n*sqrt(n))
可以在很短的时间内实现快速的插入、删除和查找。
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
#include<ext/rope>
using namespace std;
using namespace __gnu_cxx;
typedef long long LL;
const int MAXN = 2e6+10;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
char s[MAXN]; rope<char> a;
signed main(){
#ifndef ONLINE_JUDGE
freopen("C:\\Users\\Administrator\\Desktop\\in.txt","r",stdin);
#endif // ONLINE_JUDGE
int n,pos=0,x; scanf("%d",&n);
while(n--){
scanf("%s",s);
if(s[0]=='M') scanf("%d",&pos);
else if(s[0]=='P') pos--;
else if(s[0]=='N') pos++;
else if(s[0]=='G'){
scanf("%d",&x);
for(int i=pos;i<pos+x;i++) putchar(a[i]); puts("");
}else if(s[0]=='I'){
scanf("%d",&x); int len=a.length();
for(int i=0;i<x;i++){
s[i]=getchar();
while(s[i]=='\n') s[i]=getchar();
}
s[x]='\0';
a.insert(pos,s);
}else if(s[0]=='D'){
scanf("%d",&x); int len=a.length();
a.erase(pos,x);
}
}
return 0;
}
本文深入探讨了rope数据结构,一种高效处理字符串操作的扩展STL组件。rope支持快速插入、删除和查找,适用于需要频繁修改长字符串的场景。文中详细介绍了rope的使用方法,包括插入、追加、提取子串、访问元素、删除和替换等操作,并提供了一段AC代码示例,展示了如何在实际问题中应用rope。
673

被折叠的 条评论
为什么被折叠?



