列表

详情


NC50987. Palindrome

描述

Andy 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.

输入描述

Your 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).

输出描述

For each test case in the input print the test case number and the length of the largest palindrome.

示例1

输入:

abcbabcbabcba
abacacbaaaab
END

输出:

Case 1: 13
Case 2: 6

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 27ms, 内存消耗: 12080K, 提交时间: 2019-11-28 23:13:51

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e6+8;
char ma[MAXN<<1],s[MAXN];
int p[MAXN<<1],cas=1;
int manacher(int len){
    int n=0,mx=0,id=0,ans=0;
    ma[n++]='$';
    ma[n++]='#';
    for(int i=0;i<len;++i){
        ma[n++]=s[i];
        ma[n++]='#';
    }ma[n]='@';
    for(int i=1;i<n;++i){
        p[i]=mx>i?min(mx-i,p[(id<<1)-i]):1;
        while(ma[i-p[i]]==ma[i+p[i]])p[i]++;
        if(mx<p[i]+i)id=i,mx=p[i]+i;
        ans=max(ans,p[i]);
    }return ans-1;
}
int main() {
    while(scanf("%s",s),s[0]^'E')
        printf("Case %d: %d\n",cas++,manacher(strlen(s)));
    return 0;
}

C++ 解法, 执行用时: 35ms, 内存消耗: 10128K, 提交时间: 2021-12-18 15:11:15

#include<bits/stdc++.h>
using namespace std;
char s[2000001];
int p[2000001],num;
int main(){
	while(cin>>s&&s[0]!='E'){
		int l=strlen(s),k=1,ml=0;
		for(int i=l;i>=0;i--)s[i+i+2]=s[i],s[i+i+1]='#';
		s[0]='*';
		for(int i=2;i<l+l+1;++i){
			int mr=k+p[k]-1;
			p[i]=min(p[2*k-i],max(mr-i+1,1));
			while(s[i-p[i]]==s[i+p[i]])++p[i];
			if(i+p[i]>k+p[k])k=i;
			if(p[i]>ml)ml=p[i];
		}
		cout<<"Case "<<++num<<": "<<ml-1<<"\n";
	}
	return 0;
}

上一题