2023-10-05 模拟赛
T385454 优秀 (good)
思路
按题意模拟即可。
时间复杂度
时间:
T385468 词典 dict
思路1
按题意模拟即可。
时空复杂度
时间:
思路2
考虑用字典树存下所有的字符串,然后再匹配的时候没考虑都一个点,暴力去找如果这个点是被删了的还是新增的还是更改过的,然后判断有没有即可。
code
#include <algorithm>
#include <iostream>
using namespace std;
const int MaxN = 60, MaxL = 20 * 60;
int nxt[MaxL][27], n, q, tot;
bool flag[MaxL];
void Insert(string s) {
int len = s.size(), p = 0;
for (int i = 0; i < len; i++) {
int c = s[i] - 'a';
(!nxt[p][c]) && (nxt[p][c] = ++tot);
p = nxt[p][c];
}
flag[p] = 1;
}
int F(int p) {
for (int i = 0; i < 26; i++) {
if (flag[nxt[p][i]]) {
return i;
}
}
return -1;
}
string Find(string s, int i, int p, int cnt) {
if (i == s.size()) {
int fn = F(p), fnn = F(nxt[p][fn]);
if (!cnt && fn != -1) {
string res;
res += char(fn + 'a');
return res;
}
return flag[p] ? "" : "oN";
}
int c = s[i] - 'a';
string res = "oN";
if (nxt[p][c]) {
string tmp = Find(s, i + 1, nxt[p][c], cnt);
if (tmp != "oN") {
res = tmp + char(c + 'a');
}
}
if (!cnt) {
// 更改
for (int c = 0; c < 26; c++) { // 枚举原来是什么
if (nxt[p][c]) {
string tmp = Find(s, i + 1, nxt[p][c], cnt + 1); // 由于是更改,所以当前下标就不能用了,应该用下一个下标配对下一个位置
if (tmp != "oN") {
res = tmp + char(c + 'a'); // 还原字符串
}
}
}
// 增加
string tmp = Find(s, i + 1, p, cnt + 1); // 由于是增加所以当前下标就不能用了,应该用下一个下标配对当前位置
if (tmp != "oN") {
res = tmp; // 由于是增加的,所以不用加上
}
// 删除
for (int c = 0; c < 26; c++) { // 枚举被删掉的是什么
if (nxt[p][c]) {
string tmp = Find(s, i, nxt[p][c], cnt + 1); // 由于是删掉,所以当前下标应该与下一个配对
if (tmp != "oN") {
res = tmp + char(c + 'a');
}
}
}
}
return res;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> q;
for (int i = 1; i <= n; i++) {
string s;
cin >> s, Insert(s);
}
for (string s, ans; q; q--) {
cin >> s;
ans = Find(s, 0, 0, 0);
reverse(ans.begin(), ans.end());
cout << ans << '\n';
}
return 0;
}
时空复杂度
时间: