分析:
给出N个字符串建树,然后给出一个母串,求出再母串中出现次数最多的子串,如果有多个,就全输出。题解:
模板题!!因为要计算出现次数,可以考虑先用map存储一些所有的子串出现次数,然后再用一个string数组存最大次数字符串。
AC代码:
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef double DBL;
typedef long double LDBL;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) ((a)*(a))
int loc;
int cnt;
string pat[222];
map<string, int> ans;
const int k = 26;
const int MAXN = 500100;
struct Node
{
Node* ch[k], *fail;
int match;
void clear()
{
memset(this, 0, sizeof(Node));
}
};
Node * que[MAXN];
struct ACAutomaton
{
Node nodes[MAXN], *root, *superRoot, *cur; //全局变量
Node * newNode() //从内存池中初始化一个结点
{
cur -> clear();
return cur++;
}
void clear() //清空整个字典树
{
cur = nodes;
superRoot = newNode();
root = newNode();
root -> fail = superRoot;
for(int i=0;i<k;i++) //superRoot为虚拟的超级根结点,所有孩子均指向实际的根结点,减少建立自动机的代码量
superRoot -> ch[i] = root;
superRoot->match = -1;
}
void insert(char *s)//插入每一个字符,match++
{
Node * t = root;
for(;*s;s++)
{
int x = *s - 'a';
if(t -> ch[x] == NULL)
t -> ch[x] = newNode();
t = t -> ch[x];
}
t -> match = loc++;
}
void build() //使用自动机前,要先生成失配指针
{
int p=0, q =0;
que[q++] = root;
while(p!=q) //BFS求失配指针【非常关键的一步,可以好好理解】
{
Node*t = que[p++];
for(int i=0;i<k;i++)
{
if(t->ch[i])
{
t -> ch[i] -> fail = t->fail ->ch[i];
que[q++] = t->ch[i];
}else
t->ch[i] = t -> fail ->ch[i];
}
}
}
void run(char *s) //计算s中模式串出现的次数
{
ans.clear();
Node * t = root;
for(; *s ; s++)
{
int x = *s - 'a';
t = t->ch[x]; //记住 t 每次迭代的值!!!便于理解
for(Node*u = t; u->match != -1;u = u->fail)
{
int tmp = u ->match;
ans[pat[tmp] ]++;
//u -> match = -1; //避免重复计算
}
}
}
};
int N;
char s[1123456];
ACAutomaton c;
string out[222];
int main()
{
while(scanf("%d", &N) && N)
{
loc = 1;
cnt = 1;
c.clear();
for(int i=1;i<=N;i++)
{
scanf("%s", &s);
pat[i] = s;
c.insert(s);
ans[s] = i;
}
c.build();
scanf("%s", &s);
c.run(s);
int index = -1;
int Max = -1;
for(int i= 1;i<=N;i++)
{
Max = max(ans[pat[i]], Max);
}
printf("%d\n", Max);
int num = 0;
for(int i=1;i<=N;i++)
{
if(ans[pat[i]] == Max)
{
out[num++] = pat[i];
}
}
for(int i=0;i<num;i++)
cout << out[i] << endl;
}
}