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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章