HDU 4763 Theme Section(KMP+枚举公共前后缀)
生活随笔
收集整理的這篇文章主要介紹了
HDU 4763 Theme Section(KMP+枚举公共前后缀)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:?http://acm.hdu.edu.cn/showproblem.php?pid=4763?
題目大意:
給你一個(gè)字符串s,存在一個(gè)
子串E同時(shí)出現(xiàn)在前綴、中間、后綴,即EAEBE這種模式,A和B可以是任意長(zhǎng)度字符串。
解題思路:
其實(shí)就是把所有公共前后綴都枚舉一遍,每次將
s同時(shí)減去前綴和后綴,再將公共前后綴作為模式串進(jìn)行kmp算法,如果能匹配到,則輸出長(zhǎng)度即可。
代碼
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 const int maxn=2e6+5; 7 8 int nxt1[maxn],nxt2[maxn],p[maxn]; 9 char s[maxn],str[maxn]; 10 11 void getnext(char *t,int len,int *nxt){ 12 int i,j; 13 i=0,j=nxt[0]=-1; 14 while(i<len){ 15 while(j!=-1&&t[i]!=t[j]) 16 j=nxt[j]; 17 nxt[++i]=++j; 18 } 19 } 20 21 bool kmp(char *s,int len1,char *t,int len2){ 22 int i,j; 23 i=j=0; 24 getnext(t,len2,nxt2); 25 while(i<len1){ 26 while(j!=-1&&s[i]!=t[j]) 27 j=nxt2[j]; 28 i++,j++; 29 if(j==len2) 30 return true; 31 } 32 return false; 33 } 34 35 int main(){ 36 int t; 37 scanf("%d",&t); 38 while(t--){ 39 scanf("%s",s); 40 int len=strlen(s); 41 getnext(s,len,nxt1); 42 int t=nxt1[len]; 43 int ans=0; 44 while(t>0){ 45 if(kmp(s+t,len-2*t,s,t)){ 46 ans=t; 47 break; 48 } 49 t=nxt1[t]; 50 } 51 printf("%d\n",ans); 52 } 53 return 0; 54 }?
轉(zhuǎn)載于:https://www.cnblogs.com/fu3638/p/8504002.html
總結(jié)
以上是生活随笔為你收集整理的HDU 4763 Theme Section(KMP+枚举公共前后缀)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。