洛谷4248 - [AHOI2013]差异

SAM 板子题。

可以发现两个串的 LCS 即在 SAM 上的 LCA 的 len ,对于每一个点统计对答案的贡献次数即可。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// =================================
// author: memset0
// date: 2019.01.17 20:59:48
// website: https://memset0.cn/
// =================================
#include <bits/stdc++.h>
#define int long long
#define ll long long
namespace ringo {
template <class T> inline void read(T &x) {
x = 0; register char c = getchar(); register bool f = 0;
while (!isdigit(c)) f ^= c == '-', c = getchar();
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
if (f) x = -x;
}
template <class T> inline void print(T x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) print(x / 10);
putchar('0' + x % 10);
}
template <class T> inline void print(T x, char c) { print(x), putchar(c); }

const int N = 1e6 + 10;
int n;
ll ans;
char s[N];

struct samStruct {
int clen, cnt, lst;
int fa[N], len[N], siz[N], ch[N][26];
std::vector <int> G[N];
inline samStruct() { cnt = lst = 1; }
inline void insert(int c) {
int f = lst, u = ++cnt; len[lst = u] = ++clen, siz[u] = 1;
while (f && !ch[f][c]) ch[f][c] = u, f = fa[f];
if (!f) return (void)(fa[u] = 1);
int s = ch[f][c];
if (len[s] == len[f] + 1) return (void)(fa[u] = s);
int p = ++cnt; len[p] = len[f] + 1, fa[p] = fa[s], fa[s] = fa[u] = p;
for (register int i = 0; i < 26; i++) ch[p][i] = ch[s][i];
while (f && ch[f][c] == s) ch[f][c] = p, f = fa[f];
}
void dfs(int u, int depth) {
int sum = 0;
for (int i = 0, v; i < G[u].size(); i++)
v = G[u][i], dfs(v, depth + len[v] - len[u]), sum += siz[v];
ans += (ll)sum * siz[u] * 2 * depth;
for (int i = 0, v; i < G[u].size(); i++)
v = G[u][i], ans += (ll)siz[v] * (sum - siz[v]) * depth;
siz[u] += sum;
}
inline void solve() {
for (int i = 2; i <= cnt; i++) G[fa[i]].push_back(i);
dfs(1, 0);
}
} sam;

void main() {
scanf("%s", s + 1), n = strlen(s + 1);
for (int i = n; i >= 1; i--) sam.insert(s[i] - 'a');
sam.solve();
ans = ((unsigned long long)n * (n - 1) * (n + 1) >> 1) - ans;
print(ans, '\n');
}

} signed main() { return ringo::main(), 0; }
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×