POI2005SZA-Template
字符串 #kmp #POI #Year2005
考虑字符串做 \(kmp\)
考虑第 \(i\) 位的答案,假设 \(p=nxt_i\),考虑 \(res_p\) 在什么情况下是合法的
当最后一个 \(res_x=res_p\) 的 \(x\) 满足 \(x\geq i-res_p\) 时,那么 \(res_i=res_p\)
同时用一个 \(la_i\) 维护答案为 \(i\) 的最后的位置,直接转移即可
// Author: xiaruize
#ifndef ONLINE_JUDGE
bool start_of_memory_use;
#endif
#include <bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
clock_t start_clock = clock();
#endif
#define int long long
#define ull unsigned long long
#define ALL(a) (a).begin(), (a).end()
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define pis pair<int, string>
#define sec second
#define fir first
#define sz(a) int((a).size())
#define Yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define No cout << "No" << endl
#define NO cout << "NO" << endl
#define mms(arr, n) memset(arr, n, sizeof(arr))
#define rep(i, a, n) for (int i = (a); i <= (n); ++i)
#define per(i, n, a) for (int i = (n); i >= (a); --i)
int max(int a, int b)
{
if (a > b)
return a;
return b;
}
int min(int a, int b)
{
if (a < b)
return a;
return b;
}
const int INF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1000000007;
const int N = 5e5 + 10;
char s[N];
int res[N], la[N];
int p[N];
int n;
void solve()
{
cin >> (s + 1);
n = strlen(s + 1);
for (int i = 2, j = 0; i <= n; i++)
{
while (j && s[j + 1] != s[i])
j = p[j];
if (s[j + 1] == s[i])
j++;
p[i] = j;
}
rep(i, 1, n)
{
res[i] = i;
if (la[res[p[i]]] >= i - res[p[i]])
res[i] = res[p[i]];
la[res[i]] = i;
}
cout << res[n] << endl;
}
#ifndef ONLINE_JUDGE
bool end_of_memory_use;
#endif
signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int testcase = 1;
// cin >> testcase;
while (testcase--)
solve();
#ifndef ONLINE_JUDGE
cerr << "Memory use:" << (&end_of_memory_use - &start_of_memory_use) / 1024.0 / 1024.0 << "MiB" << endl;
cerr << "Time use:" << (double)clock() / CLOCKS_PER_SEC * 1000.0 << "ms" << endl;
#endif
return 0;
}