考虑到如果没有本质不同,我们可以直接统计这样的子串个数。即线性扫一遍,并同时记录每一个数当前出现的次数。对于一段极长的合法子串,设其长度为 ,对答案的贡献为 。
进一步地,如果加上本质不同,思考做法。发现仍然是好做的,只需要上一个广义 SAM 就可以了。最后就是本质不同子串个数,统计方式是 ,这是典的。
Code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using i128 = __int128;
using PII = pair<int, int>;
using PLL = pair<ll, ll>;
#define fi first
#define se second
constexpr ll inf = (1ll << 62);
constexpr int N = 1e6 + 10;
template <typename T> void chkmax(T& a, T b) { a = max(a, b); }
template <typename T> void chkmin(T& a, T b) { a = min(a, b); }
int tot, ch[N][10], lk[N], len[N], lst;
int clone(int q) {
int cl = ++tot;
lk[cl] = lk[q];
memcpy(ch[cl], ch[q], sizeof(ch[cl]));
return cl;
}
int extend(int x) {
if (ch[lst][x]) {
int p = lst, q = ch[p][x];
if (len[p] + 1 == len[q]) {
return q;
}
int cl = clone(q); len[cl] = len[p] + 1;
lk[q] = cl;
while (~p && ch[p][x] == q) ch[p][x] = cl, p = lk[p];
return cl;
}
int cur = ++tot;
len[cur] = len[lst] + 1;
while (~lst && !ch[lst][x]) ch[lst][x] = cur, lst = lk[lst];
if (lst == -1) lk[cur] = 0;
else {
int p = lst, q = ch[p][x];
if (len[p] + 1 == len[q]) lk[cur] = q;
else {
int cl = clone(q); len[cl] = len[p] + 1;
lk[cur] = lk[q] = cl;
while (~p && ch[p][x] == q) ch[p][x] = cl, p = lk[p];
}
}
return cur;
}
void solve() {
int n;
cin >> n;
vector<bool> flag(n + 1);
vector<int> a(n + 1), cnt(n + 1);
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
if (a[i] == a[i - 1]) {
cnt[i] = cnt[i - 1] + 1;
} else {
cnt[i] = 1;
}
chkmin(cnt[i], a[i]);
if (cnt[i] == a[i]) {
if (flag[i - a[i]] && a[i - a[i]] != a[i]) {
lst = extend(a[i]);
} else {
lst = 0;
lst = extend(a[i]);
}
flag[i] = true;
}
}
ll ans = 0;
for (int i = 1; i <= tot; i++) {
ans += len[i] - len[lk[i]];
}
cout << ans << "\n";
}
int main() {
lk[0] = -1;
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}