首页 > 代码库 > hdu1238 kmp
hdu1238 kmp
You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
InputThe first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
OutputThere should be one line per test case containing the length of the largest string found.
Sample Input
2 3 ABCD BCDFF BRCD 2 rose orchid
Sample Output
2 2
题意:找n个字符串里的公共子串,相反方向的也算公共子串
题解:枚举第一个的子串和后面的进行kmp
(1a的感觉真tm爽)
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<vector> #include<cstdio> #include<iomanip> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define pi acos(-1) #define ll long long #define mod 10007 #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 using namespace std; const double g=10.0,eps=1e-9; const int N=100+5,maxn=(1<<18)-1,inf=0x3f3f3f3f; int Next[N],slen,plen; string a[N],ptr,str; void getnext() { int k=-1; Next[0]=-1; for(int i=1;i<slen;i++) { while(k>-1&&str[k+1]!=str[i])k=Next[k]; if(str[k+1]==str[i])k++; Next[i]=k; } } bool kmp() { int k=-1; for(int i=0;i<plen;i++) { while(k>-1&&str[k+1]!=ptr[i])k=Next[k]; if(str[k+1]==ptr[i])k++; if(k==slen-1)return 1; } return 0; } int main() { ios::sync_with_stdio(false); cin.tie(0); // cout<<setiosflags(ios::fixed)<<setprecision(2); int t,n; cin>>t; while(t--){ cin>>n; for(int i=0;i<n;i++)cin>>a[i]; int ans=0; for(int i=1;i<=a[0].size();i++) { for(int j=0;j<=a[0].size()-i;j++) { str=a[0].substr(j,i); slen=str.size(); getnext(); bool flag=1; for(int k=1;k<n;k++) { ptr=a[k]; plen=a[k].size(); if(kmp())continue; reverse(ptr.begin(),ptr.end()); if(kmp())continue; flag=0; break; } if(flag)ans=max(ans,slen); } } cout<<ans<<endl; } return 0; }
hdu1238 kmp
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。