http://acm.hdu.edu.cn/showproblem.php?pid=5510
题目大意:
S1~Sn n个串 问满足存在一个Sj不是Si子串(0<j<i,0<i<n) 的最大i是多少
分析:
kmp暴力 求最大的i嘛 从后向前找 找到一个不匹配的直接退出就好 小优化 相邻两个串如果短的串是长串的子串 那么在匹配是短串就不再需要匹配了
AC代码:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include<list>
#include <bitset>
#include <climits>
#include <algorithm>
#define gcd(a,b) __gcd(a,b)
#define mset(a,n) memset(a,n,sizeof(a))
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
typedef long long LL;
const LL mod=1e9+7;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
using namespace std;
int Next[1000010];
char str[505][2005];
int vis[505];
void get_Next(char *str){
int n=strlen(str);
int j=-1;
Next[0]=-1;
for (int i=1;i<n;i++){
while (j>=0&&str[i]!=str[j+1]) j=Next[j];
if (str[i]==str[j+1]) j++;
Next[i]=j;
}
}
int KMP(char *str2,char *str1){
get_Next(str2);
int len1=strlen(str1);
int len2=strlen(str2);
int j=-1;
for (int i=0;i<len1;i++){
while (j>=0&&str1[i]!=str2[j+1]) j=Next[j];
if (str1[i]==str2[j+1]) j++;
if (j==len2-1) return 1;
}
return 0;
}
int main()
{
int t;
scanf ("%d",&t);
int cc=1;
while (t--){
mset(vis,0);
int n;
scanf ("%d",&n);
for (int i=0;i<n;i++) scanf ("%s",str[i]);
for (int i=1;i<n;i++) if (KMP(str[i-1],str[i])) vis[i-1]=1;
int flag=0;
for (int i=n-1;i>=0;i--){
for (int j=i-1;j>=0;j--){
if (vis[j]) continue;
int len=KMP(str[j],str[i]);
if (!len){
printf ("Case #%d: %d\n",cc++,i+1);
flag=1;
break;
}
}
if (flag) break;
}
if (!flag) printf ("Case #%d: %d\n",cc++,-1);
}
return 0;
}