P4081 [USACO17DEC]Standing Out from the Herd P

给定字符串集合,求只属于该字符串的本质不同的非空子串的个数。

广义SAM,插入的时候记录每个初始结点对应的$i$个字符串。向上跑$link$,如果遇到$endpos$里包含其他不属于$i$字符串。标记一下$-1$,并且往后都无效。如果遇到$-1$,表示后面已经标记为$-1$了。不用继续标记。最多标记$|S|$次。最后遍历一遍合法$endpos$即可

代码
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mk make_pair
const int N = 1e6 + 10;
const int mod = 1e9 + 7;

const int SN = 2e6 + 10;
const int SM = 26;
int vis[SN];
struct SAM
{
int trans[SN][SM], link[SN], maxlen[SN], pre, scnt;
SAM() { pre = scnt = 1; }
void insert(int id)
{
int cur = ++scnt;
maxlen[cur] = maxlen[pre] + 1;
int u = pre;
pre = cur;
for (; u && !trans[u][id]; u = link[u])
trans[u][id] = cur;
if (!u)
link[cur] = 1;
else
{
int x = trans[u][id];
if (maxlen[x] == maxlen[u] + 1)
link[cur] = x;
else
{
int nc = ++scnt;
maxlen[nc] = maxlen[u] + 1;
link[nc] = link[x];
link[cur] = link[x] = nc;
memcpy(trans[nc], trans[x], sizeof(trans[x]));
for (; u && trans[u][id] == x; u = link[u])
trans[u][id] = nc;
}
}
// pre = cur;
}
void update(int u, int p)
{
for (; u && vis[u] != -1 && vis[u] != p; u = link[u])
{
if (vis[u] > 0)
vis[u] = -1;
else
vis[u] = p;
}
}
} sam;
ll ans[SN];
int n, len[N];
char t[N], s[N];
int tot;
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
sam.pre = 1;
scanf("%s", t);
len[i] = strlen(t);
for (int j = 0; j < len[i]; j++)
s[++tot] = t[j], sam.insert(t[j] - 'a');
}
tot = 0;
for (int i = 1; i <= n; i++)
{
int u = 1;
for (int j = 0; j < len[i]; j++)
{
u = sam.trans[u][s[++tot] - 'a'];
sam.update(u, i);
}
}
for (int i = 2; i <= sam.scnt; i++)
ans[vis[i]] += sam.maxlen[i] - sam.maxlen[sam.link[i]];
for (int i = 1; i <= n; i++)
printf("%lld\n", ans[i]);
}