USACO Section 1.3.5 Calf Flac

题目

Calf Flac

It is said that if you give an infinite number of cows an infinite number of heavy-duty laptops (with very large keys), that they will ultimately produce all the world's great palindromes. Your job will be to detect these bovine beauties.

Ignore punctuation, whitespace, numbers, and case when testing for palindromes, but keep these extra characters around so that you can print them out as the answer; just consider the letters `A-Z' and `a-z'.

Find the largest palindrome in a string no more than 20,000 characters long. The largest palindrome is guaranteed to be at most 2,000 characters long before whitespace and punctuation are removed.

PROGRAM NAME: calfflac

INPUT FORMAT

A file with no more than 20,000 characters. The file has one or more lines which, when taken together, represent one long string. No line is longer than 80 characters (not counting the newline at the end).

SAMPLE INPUT (file calfflac.in)

Confucius say: Madam, I'm Adam.

OUTPUT FORMAT

The first line of the output should be the length of the longest palindrome found. The next line or lines should be the actual text of the palindrome (without any surrounding white space or punctuation but with all other characters) printed on a line (or more than one line if newlines are included in the palindromic text). If there are multiple palindromes of longest length, output the one that appears first.

SAMPLE OUTPUT (file calfflac.out)

11
Madam, I'm Adam

思路

找回文串,首先想到便是枚举中间,向两头扩展。

这个题目麻烦的地方在于有很多干扰的字符,这时处理的方法有两种:

第一在最开始把那些垃圾字符放一边,最后输出的时候补上。

第二最开始不用处理,而是扩展的时候进行判断是不是合法字符。

听上去第二种简单一点,但是真正写起来第一种的优势就很明显了,因为第二种在枚举的时候要判断,扩展的时候要判断,如果是复制粘贴的代码的话一处错了还得改别处。

总之很蛋疼。我两种方法都写了,但是第一种代码短了差不多20行。下面贴的也是第一种的。

代码

/*
ID: zhrln1
LANG: C++
TASK: calfflac
*/
#include <cstdio>
char s[22222],ss[22222],ch;
int l,ls,b[22222];
int trun(char c){
	if (c>='a' && c<='z') return c;
	if (c>='A' && c<='Z') return c+'a'-'A';
	return 0;
}
int main(){
	freopen("calfflac.in","r",stdin);
	freopen("calfflac.out","w",stdout);
	ss[0]=s[0]='#';
	while (scanf("%c",&ch)!=EOF){
		ss[++ls]=ch;
		if (trun(ch)) {
			s[++l]=trun(ch);
			b[l]=ls;
        }
	}
	int ans=1,ansi=1,j1,j2;
	for (int i(2);i<=l;i++){
		for (j1=i,j2=i;j1>1 && j2<l && s[j1-1]==s[j2+1];j1--,j2++);
		if (j2-j1+1>ans) {
			ans=j2-j1+1;
			ansi=j1;
		}
		if (s[i]!=s[i+1]) continue;
		for (j1=i,j2=i+1;j1>1 && j2<l && s[j1-1]==s[j2+1];j1--,j2++);
		if (j2-j1+1>ans){
			ans=j2-j1+1;
			ansi=j1;
		}
	}
	printf("%d\n",ans);
	int p=0;
	for (int i(b[ansi]);p<ans;i++){
		printf("%c",ss[i]);
		if (trun(ss[i])) p++;
	}
	printf("\n");
	return 0;
}
相关文章
相关标签/搜索