子串
(File IO): input:sub.in output:sub.out
Time Limits: 1000 ms Memory Limits: 524288 KB
Description
Input
Output
Sample Input
4
5
ab
abc
zabc
abcd
zabcd
4
you
lovinyou
aboutlovinyou
allaboutlovinyou
5
de
def
abcd
abcde
abcdef
3
a
ba
ccc
Sample Output
4
-1
4
3
Data Constraint
解题思路
此题一看就是KMP
对于你要判断i的字符串是否符合要求,对于前面的j,k,(i > j > k)k串是j串的子串:
- 如果k串是i串的子串,j串不一定是i串的子串
- 如果k串不是i串的子串,那么j串必定不是i串的子串
也就是说,当我们确定了x串是y串的子串(x < y),判断后面的串是否符合要求就无需再用x串判断了
现在我们用i串去判断当前答案后面的串j,如果i串是j串的子串,那么就可以停止搜索,否则就更新答案继续搜索。O(TNL),L为串长。
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct juro{
char st[2010];
int len;
}str[510];
int t,n,p[510][2010];
int main()
{
freopen("sub.in","r",stdin);
freopen("sub.out","w",stdout);
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
char ch=' ';
str[i].len=0;
for(;ch < 'a' || ch > 'z';ch=getchar());
for(;ch >= 'a' && ch <= 'z';ch=getchar())str[i].st[++str[i].len]=ch;
p[i][1]=0;
int y=0;
for(int x=2;x<=str[i].len;x++)
{
while(y && str[i].st[x]!=str[i].st[y+1])y=p[i][y];
if(str[i].st[x]==str[i].st[y+1])y++;
p[i][x]=y;
}
}
int ans=-1;
for(int i=1;i<n;i++)
{
int s=max(i+1,ans+1);
for(int j=s;j<=n;j++)
{
int x=0;
bool q=0;
for(int y=1;y<=str[j].len;y++)
{
while(x && str[i].st[x+1]!=str[j].st[y])x=p[i][x];
if(str[i].st[x+1]==str[j].st[y])x++;
if(x==str[i].len)
{
q=1;
break;
}
}
if(q)break;
ans=max(ans,j);
}
if(ans==n)break;
}
printf("%d\n",ans);
}
}