HDU 2594 Simpsons’ Hidden Talents(KMP)
阿新 • • 發佈:2017-10-13
lan hid ima .com i++ ons namespace 兩個 get
http://acm.split.hdu.edu.cn/showproblem.php?pid=2594
題意:
給出兩個字符串,求最長的子串使得該子串同時是第一個字符串的前綴和第二個字符串的後綴。
思路:
這道題本來就是KMP算法的一個應用吧。
在用kmp進行匹配時,文本串的最後一串字符肯定和匹配串起始的一串字符是相等的。
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<cstdio> 5 #include<vector> 6#include<stack> 7 #include<queue> 8 #include<cmath> 9 #include<map> 10 #include<set> 11 using namespace std; 12 typedef long long ll; 13 typedef pair<int,int> pll; 14 const int INF = 0x3f3f3f3f; 15 const int maxn = 50000 + 5; 16 17 int n,m; 18 int ans;19 int f[maxn]; 20 char s1[maxn],s2[maxn]; 21 22 23 void kmp(char* T, char* P) 24 { 25 f[0]=0; f[1]=0; 26 for(int i=1;i<m;i++) 27 { 28 int j=f[i]; 29 while(j && P[i]!=P[j]) j=f[j]; 30 f[i+1]= P[i]==P[j]?j+1:0; 31 } 32 33 int j=0; 34 for(int i=0;i<n;i++) 35 { 36 while(j && P[j]!=T[i]) j=f[j]; 37 if(P[j]==T[i]) j++; 38 if(i==n-1) ans=j; 39 if(j==m) j=f[j]; 40 } 41 } 42 43 int main() 44 { 45 //freopen("in.txt","r",stdin); 46 while(~scanf("%s%s",s2,s1)) 47 { 48 n=strlen(s1); 49 m=strlen(s2); 50 ans=-1; 51 kmp(s1,s2); 52 if(!ans) puts("0"); 53 else 54 { 55 for(int i=0;i<ans;i++) printf("%c",s2[i]); 56 printf("% d\n",ans); 57 } 58 } 59 return 0; 60 }
HDU 2594 Simpsons’ Hidden Talents(KMP)