省选字符串算法总结

众做周知,$\text{LiM}$字符串没学好。
所以这里会用来整理一些知名字符串算法。


$\mathcal{KMP}$

这里不写了…还有一堆$fail$数组的妙用。


$\mathcal{AC自动机}$

在$\text{Trie}$上跑$\text{KMP}$.
建立$trie$图然后暴跳(

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
/**
* @Author: Mingyu Li
* @Date: 2019-03-31T13:59:13+08:00
* @Last modified by: Mingyu Li
* @Last modified time: 2019-03-31T14:07:19+08:00
*/
#include <bits/stdc++.h>
#define Go(i , x , y) for(register int i = x; i <= y; i++)
#define God(i , y , x) for(register int i = y; i >= x; i--)
using namespace std;

const int N = 500000 + 5;
struct AC_automaton {
int trie[N][26] , val[N] , fail[N] , cnt;
void insert(char *s) {
int l = strlen(s);
int now = 0;
for(int i = 0; i < l; i++) {
if(trie[now][s[i] - 'a'] == 0)
trie[now][s[i] - 'a'] = ++cnt;
now = trie[now][s[i] - 'a'];
}
++val[now];
}
void Build() {
queue<int> q;
Go(i, 0, 25)
if(trie[0][i])
q.push(trie[0][i]), fail[trie[0][i]] = 0;

while(!q.empty()) {
int u = q.front(); q.pop();
Go(i, 0, 25) {
if(trie[u][i]) fail[trie[u][i]] = trie[fail[u]][i], q.push(trie[u][i]);
else trie[u][i] = trie[fail[u]][i];
}
}
}
int Query(char* t) {
int ans = 0;
int l = strlen(t);
int now = 0;
for(int i = 0; i < l; i++) {
now = trie[now][t[i] - 'a'];
for(int t = now; t && ~val[t]; t = fail[t]) ans += val[t] , val[t] = -1;
}
return ans;
}
}AC;

int n;
char s[N<<1];
int main() {
scanf("%d" , &n);
Go(i, 1, n) {
scanf("%s" , s);
AC.insert(s);
}
AC.Build();
scanf("%s" , s);
cout << AC.Query(s) << endl;
return 0;
}

评论

Your browser is out-of-date!

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

×