CF1200E Compress Words
Ryc12345678910 · · 题解
CF1200E Compress Words 题解
题意
给出
题解
考虑 KMP。假设现在的答案为
为了防止越界问题,我们人为在中间加一个特殊符号。
然后你自信的交了一发,发现 TLE on test 3。于是开始考虑如何优化。注意到每次其实只需要
然后你就过了。
代码
#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
const int N = 1e6 + 5;
int pi[N];
inline void prefix(string s) {
int l = s.size();
for (int i = 1; i < l; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) j = pi[j - 1];
if (s[i] == s[j]) j++;
pi[i] = j;
}
}
inline string substr(string s, int len) {
string res = "";
for (int i = len; i < s.size(); i++) res += s[i];
return res;
}
namespace Lemon {
const int N = 1e5 + 5;
string s[N];
inline void solve() {
int n; cin >> n;
for (int i = 1; i <= n; i++) cin >> s[i];
string ans = s[1];
for (int i = 2; i <= n; i++) {
int lens = min((int)ans.size(), (int)s[i].size());
string t = s[i] + "#" + ans.substr(ans.size() - lens);
prefix(t);
int k = pi[t.size() - 1];
ans += s[i].substr(k);
}
cout << ans;
}
}
signed main() {
IOS;
int t = 1;
// cin >> t;
while (t--) Lemon::solve();
return 0;
}