这是一道简单的AC自动机模板题。
用于检测正确性以及算法常数。
为了防止卡OJ,在保证正确的基础上只有两组数据,请不要恶意提交。
管理员提示:本题数据内有重复的单词,且重复单词应该计算多次,请各位注意
给定n个模式串和1个文本串,求有多少个模式串在文本串里出现过。
第一行一个n,表示模式串个数;
下面n行每行一个模式串;
下面一行一个文本串。
输出格式:一个数表示答案
subtask1[50pts]:∑length(模式串)<=10^6,length(文本串)<=10^6,n=1;
subtask2[50pts]:∑length(模式串)<=10^6,length(文本串)<=10^6;
字符串问题的涉及还是上个暑假的时候,这里就码一下;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 2000005
#define inf 0x7fffffff
//#define INF 1e18
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9 + 7;
#define Mod 1000000000
#define sq(x) (x)*(x)
#define eps 1e-3
typedef pair<int, int> pii;
#define pi acos(-1.0)
//const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
typedef pair<int, int> pii;
inline ll rd() {
ll x = 0;
char c = getchar();
bool f = false;
while (!isdigit(c)) {
if (c == ‘-‘) f = true;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + (c ^ 48);
c = getchar();
}
return f ? -x : x;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a%b);
}
ll sqr(ll x) { return x * x; }
/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
if (!b) {
x = 1; y = 0; return a;
}
ans = exgcd(b, a%b, x, y);
ll t = x; x = y; y = t - a / b * y;
return ans;
}
*/
struct Tree {
int fail;
int vis[26];
int end;
}ac[maxn];
int cnt = 0;
inline void build(string s) {
int l = s.length();
int now = 0;
for (int i = 0; i < l; i++) {
if (ac[now].vis[s[i] - ‘a‘] == 0)
ac[now].vis[s[i] - ‘a‘] = ++cnt;
now = ac[now].vis[s[i] - ‘a‘];
}
ac[now].end += 1;
}
void getfail() {
queue<int>q;
for (int i = 0; i < 26; i++) {
if (ac[0].vis[i] != 0) {
ac[ac[0].vis[i]].fail = 0;
q.push(ac[0].vis[i]);
}
}
while (!q.empty()) {
int u = q.front(); q.pop();
for (int i = 0; i < 26; i++) {
if (ac[u].vis[i]) {
ac[ac[u].vis[i]].fail = ac[ac[u].fail].vis[i];
q.push(ac[u].vis[i]);
}
else {
ac[u].vis[i] = ac[ac[u].fail].vis[i];
}
}
}
}
int query(string s) {
int l = s.length();
int now = 0, ans = 0;
for (int i = 0; i < l; i++) {
now = ac[now].vis[s[i] - ‘a‘];
for (int t = now; t&&ac[t].end != -1;t=ac[t].fail) {
ans += ac[t].end; ac[t].end = -1;
}
}
return ans;
}
int main() {
//ios::sync_with_stdio(0);
int n; rdint(n); string s;
for (int i = 1; i <= n; i++) {
cin >> s; build(s);
}
ac[0].fail = 0;
getfail();
cin >> s;
cout << query(s) << endl;
return 0;
}
原文:https://www.cnblogs.com/zxyqzy/p/10202450.html