HDOJ 5340 Three Palindromes

来源:互联网 发布:网络协议的作用 编辑:程序博客网 时间:2024/05/16 10:49
Problem Description
Can we divided a given string S into three nonempty palindromes?
 

Input
First line contains a single integer T20 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
 

Output
For each case, output the "Yes" or "No" in a single line.
 

Sample Input
2abcabaadada
 

Sample Output
Yes

No

题目的意思是看一个字符串可以不可以分成三个回文串、

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int p[44000],n;char str[44444];void pk(){    int i;    int mx = 0;    int Id;    for(i=1; i<n; i++)    {        if( mx > i )            p[i] = min( p[2*Id-i], mx-i );                else            p[i] = 1;        for(; str[i+p[i]] == str[i-p[i]]; p[i]++)            ;        if( p[i] + i > mx )        {            mx = p[i] + i;            Id = i;        }    }}char ch[22222];int p2[22222];bool dp[22222][4];int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%s",ch+1);        int len=strlen(ch+1);        int len2=len*2+1;        for(int i=1;i<=len;i++)        {            str[i*2-1]='#';            str[i*2]=ch[i];        }        str[len2]='#';        str[len2+1]='\0';        str[0]='$';        n=len2+1;        pk();        bool ans=false;        for(int i=1;i<=len-2;i++)        {            if(ans)break;            int center=i+1;            if(p[center]-1==i)            {                for(int j=i+1;j<=len-1;j++)                {                    if(ans)break;                    int ct=((i+1)*2+j*2)/2;                    if(p[ct]-1>=j-i)                    {                        int nct=len+(j+1);                        if(p[nct]-1>=len-j)ans=true;                    }                }            }        }        if(ans)printf("Yes\n");        else printf("No\n");    }}

一个时间为(log n)的回文串的算法:https://www.baidu.com/link?url=xBybNJBbPas7PgjpomF-URWaxZ30x3qxSmGJ9nRbf2BBmiqZJ1MiP45hZI72Y_KBQt4W1STz6T7E7hEfFHdC8O0BvEkniYcKd12kg4zXzDW&wd=&eqid=8306f46b0000f6600000000455bd9c27

0 0