我的是 O(26n) 的做法,思路是如果两个极小块的首尾字符相同则合并。
代码中
if (pos[j - 1] && s[j - 1] == s[j]) pos[i] = pos[j - 1];
是用来合并的,但我加不加这一句都能过。是数据弱了吗?我的这个操作假了吗?(慌)
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e6 + 10;
int n, ans[N], pos[N];
string s;
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> s;
s = ' ' + s;
for (int i = 1; i <= n; i++) {
for (int j = i - 1; j; j = pos[j] - 1) {
if (s[j] == s[i]) {
pos[i] = j;
if (pos[j - 1] && s[j - 1] == s[j]) pos[i] = pos[j - 1];
ans[i] = 1 + ans[j - 1];
// printf("%d: ans[%d]: %d\n", i, j - 1, ans[j - 1]);
break;
}
if (!pos[j]) break;
}
}
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += ans[i];
// printf("ans[%d]: %d\n", i, ans[i]);
}
cout << sum;
return 0;
}