AT_abc411_d [ABC411D] Conflict 2 题解
题目大意:
有一台主机和
现有
询问分以下
- 用服务器
p 的字符串代替主机字符串。 - 在服务器
p 的字符串后增加字符串s 。 - 用主机字符串代替服务器
p 的字符串。思路:
这道题目直接模拟是不行的。
本人就进坑了。我们可以借助树状数组,优化操作的时间复杂度。所以,我们需要一个pc 数组记树上每个节点的字符串,用一个pos 数组记每个字符串存储在树上的哪个位置,用一个father 数组记每个节点的父亲节点,还要用一个server 记主机在树上的编号。
于是3 个操作就变成了这样: - 将
server 的值赋给pos_p 。 - 新建一个节点并建立关系,令
pos_p 为此时的节点数量。 - 将
pos_p 的值赋给server 。
时间复杂度
代码:
#include <bits/stdc++.h>
using namespace std;
int n, q, len, father[200010], pos[200010], sv;//sv为server的简写,len表示长度
string pc[200010];
int main(int argc, const char *argv[]) {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
while (q--) {
int opt, p;
cin >> opt >> p;
if (opt == 1)
pos[p] = sv;
else
if (opt == 2) {
len++;
cin >> pc[len];
father[len] = pos[p];
pos[p] = len;
}
else
sv = pos[p];
}
stack<int> s;//利用栈找出前往根节点的整条路径上的所有字符串,倒序输出即可。
while (sv != 0) {
s.push(sv);
sv = father[sv];
}
while (!s.empty()) {
cout << pc[s.top()];
s.pop();
}
return 0;
}