原题链接:点击打开链接
Problem 2128 最长子串
Accept: 179 Submit: 651
Time Limit: 3000 mSec Memory Limit : 65536 KB
Problem Description
问题很简单,给你一个字符串s,问s的子串中不包含s1,s2...sn的最长串有多长。
Input
输入包含多组数据。第一行为字符串s,字符串s的长度1到10^6次方,第二行是字符串s不能包含的子串个数n,n<=1000。接下来n行字符串,长度不大于100。
字符串由小写的英文字符组成。
Output
最长子串的长度
Sample Input
lgcstraightlalongahisnstreet
5
str
long
tree
biginteger
ellipse
5
str
long
tree
biginteger
ellipse
Sample Output
12
看到数据范围我一下子就想到了AC自动机。。。然后因为对AC自动机不太理解,没写出来。之后才知道这道题暴力就能过了。
对于主串S,当匹配了子串Tj时,我们可以得到一个符合要求的子串的长度len=i-low-1 (low:离i最近的匹配的子串Tk的开始位置+1,保证从i-1到low这段区间没有可匹配模式串的子串),然后更新low。在所有的匹配结束之后,如果low<strlen(S)的话,我们还可以得到一个长度len=strlen(S)-low。而题目要求的答案就是所有的len中最大的那一个。
AC代码:
#include <cstring>
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <math.h>
#include <set>
#include <time.h>
using namespace std;
int Next[101000][26],f[101000],tot;
int fg[101000];
int newnode()
{
memset(Next[tot],0,sizeof(Next[tot]));
fg[tot]=0;
return tot++;
}
void Insert(int p,char *s)//构造字典树
{
int i;
for(i=0; s[i]; ++i)
{
int a=s[i]-'a';
if(!Next[p][a])
Next[p][a]=newnode();
p=Next[p][a];
}
fg[p]=i;
}
void wa()//构造失配指针
{
f[0]=0;
queue<int>q;
for(int i=0; i<26; ++i)
{
f[Next[0][i]]=0;
if(Next[0][i])
q.push(Next[0][i]);
}
while(!q.empty())
{
int p=q.front();
q.pop();
for(int i=0; i<26; ++i)
{
if(Next[p][i])
{
f[Next[p][i]]=Next[f[p]][i];
q.push(Next[p][i]);
}
else Next[p][i]=Next[f[p]][i];
}
}
}
int ac(char *s)
{
int p=0;
int ans=0;
int low=0,i;
for(i=1; s[i]; ++i)
{
int a=s[i]-'a';
p=Next[p][a];
int temp=p;
while(temp)
{
if(fg[temp])
{
// printf("%d:%d\n",i,low);
ans=max(i-low-1,ans);//取最大的那个len
low=max(low,i-fg[temp]+1);//取最靠近i的low
/*
low不取最大的话,对于数据
aaaab
2
aaaab
a
会出现在匹配了aaaab之后,low会回到1的位置
*/
}
temp=f[temp];
}
}
return max(ans,i-low-1);
}
char s[1010000];
char a[120];
int main()
{
int n;
// freopen("input.txt","r",stdin);
while(~scanf("%s",s+1))
{
tot=0;
newnode();
scanf("%d",&n);
for(int i=0; i<n; ++i)
{
scanf("%s",a);
Insert(0,a);
}
wa();
printf("%d\n",ac(s));
}
return 0;
}