hdu 5340 最長迴文子串變形,
http://acm.hdu.edu.cn/showproblem.php?pid=5340
Problem DescriptionCan we divided a given string S into three nonempty palindromes?
InputFirst line contains a single integer T≤20 which denotes the number of test cases.
For each test case , there is an single line contains a string S which only consist of lowercase English letters.1≤|s|≤20000
OutputFor each case, output the "Yes" or "No" in a single line.
Sample Input
2abcabaadada
Sample Output
YesNo
<pre name="code" class="cpp">/**hdu 5340 最長迴文子串變形題目大意:給定一個字串問是否正好可以分成三個迴文子串(不可為空串)解題思路:如果直接枚舉判斷時間複雜度為O(n^3)。可以利用Manacher演算法求出所有0~i為迴文串和j~n-1為迴文串的i和j 最後枚舉這兩個位置利用原本求出的r[i],判斷中間的是不是迴文串即可。複雜度不會超過O(n^2)*/#include <stdio.h>#include <string.h>#include <algorithm>#include <iostream>using namespace std;const int maxn=101005;char s[maxn],a[maxn*2];int c1[maxn*2],c2[maxn*2];///0~i滿足迴文的所有i;j~n-1滿足迴文的所有j int r[maxn*2],len;/** * 求最長迴文子串O(n) * abaaba * i: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 * a[i]: $ # a # b # a # a # b # a # * r[i]: 1 1 2 1 4 1 2 7 2 1 4 1 2 1 * answer=(max(r[i]-1)) */ void Manacher(){ int l=0; a[l++]='$'; a[l++]='#'; for(int i=0; i<len; i++) { a[l++]=s[i]; a[l++]='#'; } a[l]=0; int mx=0,id=0; for(int i=0; i<l; i++) { r[i]=mx>i?min(r[2*id-i],mx-i):1; while(a[i+r[i]]==a[i-r[i]])r[i]++; if(i+r[i]>mx) { mx=i+r[i]; id=i; } }}int main(){ int T; scanf("%d",&T); while(T--) { scanf("%s",s); len=strlen(s); Manacher(); int l1=0,l2=0; for(int i=1; i<2*len+2; i++) { if(r[i]==i&&i!=1) { c1[++l1]=i-1+r[i]; } if(r[i]==2*len+2-i&&i!=2*len+1) { c2[++l2]=i-(r[i]-1); } } int flag=1; for(int i=l1; i>=1&&flag; i--) { for(int j=1; j<=l2&&flag; j++) { int ll=c1[i]+1; int rr=c2[j]-1; if(ll>rr)continue; int tmp=(rr+ll)/2; if(r[tmp]-1==0)continue; if(r[tmp]>=(rr-ll+2)/2) { flag=0; } } } if(flag)puts("No"); else puts("Yes"); } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。