您的位置:首页 > 其它

POJ - 3974 Palindrome

2018-02-25 20:23 357 查看
Palindrome
Time Limit: 15000MS Memory Limit: 65536K
Total Submissions: 10782 Accepted: 4097
DescriptionAndy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?" 

A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not. 

The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!". 

If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.InputYour program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string "END" (quotes for clarity). 
OutputFor each test case in the input print the test case number and the length of the largest palindrome. 
Sample Inputabcbabcbabcba
abacacbaaaab
ENDSample OutputCase 1: 13
Case 2: 6求最长回文字串的长度
裸menecher#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <algorithm>
#define ll long long
#define max_ 1001000
#define inf 0x3f3f3f3f
#define mod 1000000007
using namespace std;
char ss[max_],s[max_*2];
int p[max_*2],casnum=0;
int main(int argc, char const *argv[]) {
while(scanf(" %s",ss)!=EOF)
{
if(ss[0]=='E')
break;
s[0]='$';
s[1]='#';
int l=strlen(ss);
for(int i=0;i<l;i++)
{
s[i+i+2]=ss[i];
s[i+i+3]='#';
}
s[l*2+2]='\0';
int mx=0,id=0;
l=strlen(s);
for(int i=0;i<=l;i++)
{
if(i<mx)
p[i]=min(p[2*id-i],mx-i);
else
p[i]=1;
while(s[i-p[i]]==s[i+p[i]])
p[i]++;
if(i+p[i]>mx)
{
mx=i+p[i];
id=i;
}
}
int maxx=-1;
for(int i=0;i<l;i++)
{
maxx=max(maxx,p[i]);
}
printf("Case %d: %d\n",++casnum,maxx-1 );
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: