USACO 1.3 Calf Flac (最长回文子串 DP动态规划)

#include <stdio.h>
#define DEBUG 0
#define TESTCASES 8

#define MAX_CHARS 20000
//原字符串
char arrayOfChars[MAX_CHARS + 1];
int numOfChars;
//过滤非字母字符并把大写字母转换成小写字母的字符串
char arrayOfLetters[MAX_CHARS + 1];  
int numOfLetters;  
int map[MAX_CHARS + 1];
//maxPalinUntil[index]表示遍历arrayOfLetters直到索引index时以arrayOfLetters[index]为最后字符的最长回文子串的长度
int maxPalinUntil[MAX_CHARS + 1]

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputx.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif
	
	numOfChars = numOfLetters = 0;  
    char cha;  
    while ( scanf("%c", &cha) != EOF ){  
        arrayOfChars[numOfChars++] = cha;  
        if (cha >= 'a' && cha <= 'z'){  
            map[numOfLetters] = numOfChars - 1;  
            arrayOfLetters[numOfLetters++] = cha;  
        }  
        else if (cha >= 'A' && cha <= 'Z'){  
            //记录下标  
            map[numOfLetters] = numOfChars - 1;  
            arrayOfLetters[numOfLetters++] = 'a' + cha - 'A';  
        }  
    }  

	int indexOfLetter;
	for (indexOfLetter = 0; indexOfLetter < numOfLetters; indexOfLetter++)
		maxPalinUntil[indexOfLetter] = 1;

	int maxIndex = 0;
	int maxLen = 0;
	for (indexOfLetter = 0; indexOfLetter < numOfLetters; indexOfLetter++){
		char letter = arrayOfLetters[indexOfLetter];
		int preIndex = indexOfLetter - 1;
		int compareIndex = preIndex - maxPalinUntil[preIndex];
		if (preIndex >= 0 && compareIndex >= 0 && letter == arrayOfLetters[compareIndex])
			maxPalinUntil[indexOfLetter] = maxPalinUntil[preIndex] + 2;
		else if (letter == arrayOfLetters[preIndex])
			maxPalinUntil[indexOfLetter] = 2;

		if (maxPalinUntil[indexOfLetter] > maxLen){
			maxLen = maxPalinUntil[indexOfLetter];
			maxIndex = indexOfLetter;
		}
	}

	printf("%d\n", maxLen);

	//确定最大回文子串在原字符串arrayOfChars中的起止位置start和end
	int end = map[maxIndex];	
	int indexOfChar;
	for (indexOfChar = end; maxLen > 0; indexOfChar--){
		int cha = arrayOfChars[indexOfChar];
		if ( (cha >= 'a' && cha <= 'z') || (cha >= 'A' && cha <= 'Z'))
			maxLen--;
	}
	int start = indexOfChar + 1;

	for (indexOfChar = start; indexOfChar <= end; indexOfChar++)
		printf("%c", arrayOfChars[indexOfChar]);
	printf("\n");

#if DEBUG
	}
#endif
	return 0;
}

你可能感兴趣的:(动态规划,USACO,1.3,flac,回文子串,Calf)