题目地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=5510
思路:设两个指针l、r,对于字符串a、b、c,若a为b的子串则下次比较时可直接比较b,c。枚举r,依次比较s[l]--s[r-1]是否为s[r]的子串,若s[i]为s[r]的子串,则l++。否则答案更新为r。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define debu
using namespace std;
string st[550];
int f[2050],t,n,cas=0;
void getfail(string s)
{
memset(f,0,sizeof(f));
for(int i=1; i<s.size(); i++)
{
int j=f[i];
while(j&&s[i]!=s[j]) j=f[j];
f[i+1]=(s[i]==s[j])?j+1:0;
}
}
int Find(string a,string s)
{
int ans=0,j=0;
getfail(s);
for(int i=0; i<a.size(); i++)
{
while(j&&a[i]!=s[j]) j=f[j];
if(a[i]==s[j]) j++;
if(j==s.size()) ans++;
}
return ans;
}
int main()
{
#ifdef debug
freopen("in.in","r",stdin);
#endif // debug
ios::sync_with_stdio(0);
cin>>t;
while(t--)
{
cin>>n;
for(int i=0; i<n; i++) cin>>st[i];
int l=0,ans=0;
for(int r=1; r<n; r++)
{
while(l<r)
{
if(Find(st[r],st[l])) l++;
else
{
ans=r;
break;
}
}
}
if(!ans) cout<<"Case #"<<++cas<<": "<<-1<<endl;
else cout<<"Case #"<<++cas<<": "<<ans+1<<endl;
}
return 0;
}