这道题十分简单,只需要使用 rope 和 vector 中两个 stl 即可。
什么是 rope?笔者的理解未必完全正确,欢迎大家来提出问题。
rope 的本质是一个可持久化平衡树,其最大特点是 rope 可以 继承上一个版本。
在 rope 中间插入或删除字符串的复杂度是 ,优于 string 的 。
复制时直接把原 rope 使用引用计数快速来避免复制,之后就算对原串还是现串进行一些修改也无伤大雅。
在末尾连接两个 rope 只需要 的复杂度,而且不会读取原串。而就算对 string 进行启发式合并,复杂度也是均摊 的。
对于这个题来说,我们发现操作 与 都是复制操作,并且 是修改操作。
而 string 来做这个题的时候,在操作 与 都是 ,而操作 是 的。在这道题目中使用 string 会因为过多的操作 与 而超时。
此时我们发现,使用 rope 的时间复杂度则是 的。于是就做完了这道题
代码及其好写,不到 行,注意 rope 需要以下使用头文件和命名空间。
#include <ext/rope>
using namespace __gnu_cxx;总代码如下。
#include <iostream>
#include <vector>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
#define int long long
const int N = 1e6 + 5;
int n,q;
rope<char> server;
vector<rope<char>> pcs;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
pcs.resize(N);
cin >> n >> q;
while(q--)
{
int type, p;
cin >> type >> p;
if(type == 1) pcs[p] = server;
else if(type == 2)
{
string s; cin >> s;
pcs[p].insert(pcs[p].size(), s.c_str(), s.size());
}
else if(type == 3) server = pcs[p];
}
for(auto it=server.begin();it!=server.end();it++)
cout << *it;
cout << '\n';
return 0;
}