题解 P1383 【高级打字机】
P1383 高级打字机
传送门
思路
看到一道可持久化的字符串操作题,我立马打了一个叫做rope的数据结构。机房dalao说这是一个用可持久化红黑树实现的数据结构,我们先来学习一下rope的用法。
首先要使用rope,需要加上一下两行:
#include<ext/rope>
using namespace __gnu_cxx;
然后我们可以定义一个字符串类型的rope,叫做crope,要这样定义:
crope now;
crope s[10];
crope支持的操作:
a.push_back(x):在crope a的末尾增加字符串xa.insert(k,x):在a的第k个字符后加入字符串xa.erase(k,x):在a的第k个字符后删除x个字符a.replace(k,x):将a的第k个字符后x的长度个字符删除,并插入xa.substr(k,x):获取a的第k个字符后的长度为x的字符串a.at(k):获取a的第k个字符(从0开始)
我们可以拿一个数组来保存历史版本(反正不卡空间),每次读入操作,执行操作,保存到第
- 对于操作
T ,我们可以使用push_back(或insert) - 对于操作
U ,我们可以直接回退到V-x 的版本 - 对于操作
Q ,我们可以使用at(或substr)
crope为什么可以通过此题呢?机房的dalao说它的复制操作是
所以这种算法可以轻松水过IOI难度
上AC代码~
#include<bits/stdc++.h>
#include<ext/rope>//头文件
using namespace __gnu_cxx;
using namespace std;
const int N=1e5+10;
crope now,x[N];//定义crope,保存现在的串与历史版本
int t,p,V;
inline char read(){
char ch=getchar();
while((ch>'U'||ch<'Q')&&(ch>'z'||ch<'a')){
ch=getchar();
}
return ch;
}
inline void solve(){//操作
char opt=read();
switch(opt) {
case 'T': {//T操作
char q=read();
now.insert(p,q);
p++;
x[++V]=now;
break;
}
case 'U': {//U操作
int q;
scanf("%d",&q);
now=x[V-q];
x[++V]=now;
break;
}
case 'Q': {//Q操作
int q;
scanf("%d",&q);
putchar(now.at(q-1));
puts("");
break;
}
}
}
signed main() {
scanf("%d",&t);
while(t--) {
solve();
}
return 0;
}
最后送出
再见qwq