POJ-1226 Substrings KMP+枚举
题目链接:http://poj.org/problem?id=1226
买一送一的题目,稍微修改POJ3450或POJ3080的代码就可以了。不过C++和G++不支持strrev()函数,因为strrev()不是ANSI C的语法,改为_strrev()就可以了。
1 //STATUS:C++_AC_0MS_172KB 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<math.h> 6 #include<iostream> 7 #include<string> 8 #include<algorithm> 9 #include<vector> 10 #include<queue> 11 #include<stack> 12 #include<map> 13 using namespace std; 14 #define LL __int64 15 #define pii pair<int,int> 16 #define Max(a,b) ((a)>(b)?(a):(b)) 17 #define Min(a,b) ((a)<(b)?(a):(b)) 18 #define mem(a,b) memset(a,b,sizeof(a)) 19 #define lson l,mid,rt<<1 20 #define rson mid+1,r,rt<<1|1 21 const int N=110,INF=0x3f3f3f3f,MOD=1999997; 22 const LL LLNF=0x3f3f3f3f3f3f3f3fLL; 23 24 char s[N][N],ans[N]; 25 int next[N],w[N]; 26 int T,n,m; 27 28 void getnext(char *a,int len) 29 { 30 int j=0,k=-1; 31 next[0]=-1; 32 while(j<len){ 33 if(k==-1 || a[k]==a[j]) 34 next[++j]=++k; 35 else k=next[k]; 36 } 37 } 38 39 int kmp(char *a,int len,int i) 40 { 41 int j,k; 42 for(j=k=0;j<w[i];j++){ 43 while(k>0 && s[i][j]!=a[k])k=next[k]; 44 if(s[i][j]==a[k])k++; 45 if(k==len)return 1; 46 } 47 return 0; 48 } 49 50 int cmp(char *a,int len) 51 { 52 int i,j,ok,k,t; 53 for(i=1;i<n;i++){ 54 ok=0; 55 if(kmp(a,len,i))ok=1; 56 if(!ok){ 57 _strrev(s[i]); 58 if(kmp(a,len,i))ok=1; 59 } 60 if(!ok)return 0; 61 } 62 return 1; 63 } 64 65 int main() 66 { 67 // freopen("in.txt","r",stdin); 68 int i,j,maxlen,lens,minlen; 69 scanf("%d",&T); 70 while(T--) 71 { 72 minlen=INF; 73 maxlen=0; 74 scanf("%d",&n); 75 for(i=0;i<n;i++){ 76 scanf("%s",s[i]); 77 w[i]=strlen(s[i]); 78 if(w[i]<minlen)minlen=w[i]; 79 } 80 for(i=0;i<w[0];i++){ 81 for(j=i+1;j<=w[0];j++){ 82 lens=j-i; 83 if(lens<=maxlen || lens>minlen)continue; 84 getnext(*s+i,lens); 85 if(cmp(*s+i,lens))maxlen=lens; 86 } 87 } 88 89 printf("%d\n",maxlen); 90 } 91 return 0; 92 }