Topic background
This is a simple AC automaton template problem.
Used to detect correctness and algorithm constants.
In order to prevent card OJ, only two sets of data are guaranteed on the correct basis, please do not commit maliciously.
Title Description
Given n pattern strings and a text string, how many pattern strings appear in the text string.
Input/output format
Input format:
The first row is an n, which indicates the number of pattern strings;
The following n rows a pattern string per line;
The following line is a text string.
Output format:
A number means an answer.
Input/Output sample
Input Sample # #:
2
A
Aa
Aa
Sample # # of output:
2
Description
Subtask1[50pts]:∑length (Pattern String) <=10^6,length (text string) <=10^6,n=1;
Subtask2[50pts]:∑length (Pattern String) <=10^6,length (text string) <=10^6;
Exercises
AC Automaton Bare Topic
Code (trie Chart)
#include <cstdio> #include <cstring> #include <iostream> using namespace std;
inline int read () {int X=0,f=1;char ch=getchar (); while (ch< ' 0 ' | |
Ch> ' 9 ') {if (ch== '-') F=-1;ch=getchar ();}
while (ch>= ' 0 ' &&ch<= ' 9 ') {x=x*10+ch-' 0 '; Ch=getchar ();}
return x*f;
} Char s[1000001];
int T,n,tot,ans;
int a[1000001][26],q[1000001],point[1000001],danger[1000001];
inline void ins () {int Now=1,l=strlen (s);
for (int i=0;i<l;i++) {int t=s[i]-' a ';
if (!a[now][t]) A[now][t]=++tot;
NOW=A[NOW][T];
} danger[now]++;
} inline void Acmach () {int head=0,tail=1;
q[1]=1;point[1]=0;
while (head!=tail) {int now=q[++head]; for (int i=0;i<26;i++) {if (A[now][i]) {Point[a[now][i]]=a[point[now]
][i];
Q[++tail]=a[now][i];
} else a[now][i]=a[point[now]][i]; }}} inline void Solve () {inT Now=1,l=strlen (s);
for (int i=0;i<l;i++) {int t=s[i]-' a ';
NOW=A[NOW][T];
for (int j=now;j&&danger[j]!=-1;j=point[j]) ans+=danger[j],danger[j]=-1;
} printf ("%d", ans);
} int main () {for (int i=0;i<26;i++) a[0][i]=1;
N=read (); tot=1;
while (n--) {scanf ("%s", s);
Ins ();
} Acmach ();
scanf ("%s", s);
Solve ();
return 0; }