小 w 的爱情密码题解
考点
kmp + 栈
题目大意
重复在
做法
O(?): 30pts :
爆搜。
O( \texttt{S1} _ {len} \times \texttt{S2} _ {len} ): 60 \sim 100 pts :
按照题意模拟,可以发现每次删除的位置 不小于上一次删除的位置减
用 kmp 匹配,每次匹配成功后就向前跳
平均时间复杂度约为
构造方法:选一个串
\texttt{S2} ,\texttt{S1} 为k 个\texttt{S2} _ {1\sim{len-1}} 连上k 个\texttt{S1} _ {len} ;
例如:\texttt{S1}= abaabaabaccc,\texttt{S2}= abac。
O( \texttt{S1} _ {len} + \texttt{S2} _ {len} ): 100 pts:
发现上一个做法的问题在于每次重新匹配时向前跳时最多
考虑将每个到位置时匹配的长度
为了方便删除,可以记录到一个 栈 里面,每次移动时以栈顶元素的
若
最后将栈里剩的输出即可。
参考程序
方便输出使用了双端队列:
#include<bits/stdc++.h>
using namespace std;
struct Node {char c; int len;};
int len1, len2;
string s1, s2;
deque<Node> st;
array<int, 101> nxt;
int main() {
//Read
cin >> s1 >> s2;
len1 = s1.length(), len2 = s2.length();
//Init
for (int i = 1, l = 0; i < len2; i++) {
while (l && s2[i] != s2[l]) l = nxt[l];
nxt[i + 1] = s2[i] == s2[l] ? ++l : l = 0;
}
//Solve
for (auto now : s1) {
int l = 0;
if (!st.empty()) l = st.back().len;
while (l && now != s2[l]) l = nxt[l];
st.push_back({now, now == s2[l] ? ++l : 0});
if (l == len2) while (l--)
st.pop_back();
}
//Answer
while (!st.empty())
cout << st.front().c, st.pop_front();
return 0;
}