USACO SEC.1.3 No.3 Calf Flac
题意:给出一篇文章,求略去其中的空格等各种字符(剩余大小写字母后)文中的最长回文子串,输出长度并打印原文中对应的字符串
核心:枚举回文串
枚举回文串的中点下标是一个比较好的方法,如果反复枚举回文起始点复杂度太大
枚举中点分为两种情况(长度为奇数和偶数),分别处理即可
本题目输入的方式略麻烦
/* ID: lsswxr1 PROG: calfflac LANG: C++ */ #include <iostream> #include <vector> #include <map> #include <list> #include <set> #include <deque> #include <stack> #include <queue> #include <algorithm> #include <cmath> #include <cctype> #include <cstdio> #include <iomanip> #include <cmath> #include <cstdio> #include <string> #include <cstring> #include <fstream> using namespace std; ///宏定义 const int INF = 1000000000; const int MAXN = 20015; const int maxn = MAXN; ///全局变量 和 函数 #define USACO #ifdef USACO #define cin fin #define cout fout #endif ////////////////////////////////////////////////////////////////////////// char src[maxn], txt[maxn]; int reflect[maxn]; int cntTxt, cntSrc; int ans1, ans2, anslen; inline bool ok(char s1, char s2) { int a1 = s1 - 'a'; int a2 = s1 - 'A'; int b1 = s2 - 'a'; int b2 = s2 - 'A'; if (a1 == b1 || a1 == b2 || a2 == b1 || a2 == b2) return true; return false; } int main() { #ifdef USACO ofstream fout ("calfflac.out"); ifstream fin ("calfflac.in"); #endif ///变量定义 string src_; cntSrc = 0; cntTxt = 0; while (getline(cin, src_)) { int len = src_.length(); for (int i = 0; i < len; i++) { src[cntSrc] = src_[i]; if ((src[cntSrc] >= 'a' && src[cntSrc] <= 'z') || (src[cntSrc] >= 'A' && src[cntSrc] <= 'Z') ) { txt[cntTxt] = src[cntSrc]; reflect[cntTxt] = cntSrc; cntTxt++; } cntSrc++; } src[cntSrc++] = '\n'; } src[cntSrc] = '\0'; bool flag; anslen = 1; for (int midpos = 0; midpos < cntTxt; midpos++) { int maxlen = 0; //奇数 int ll = midpos - 1; int rr = midpos + 1; maxlen = 1; while (ll >= 0 && rr < cntTxt) { if (ok(txt[ll], txt[rr])) { maxlen += 2; ll--; rr++; } else break; } if (maxlen > anslen) { anslen = maxlen; ans1 = reflect[ll + 1]; ans2 = reflect[rr - 1]; } //偶数 ll = midpos - 1; rr = midpos; maxlen = 0; while (ll >= 0 && rr < cntTxt) { if (ok(txt[ll], txt[rr])) { maxlen += 2; ll--; rr++; } else break; } if (maxlen > anslen) { anslen = maxlen; ans1 = reflect[ll + 1]; ans2 = reflect[rr - 1]; } } cout << anslen << endl; for (int i = ans1; i <= ans2; i++) { cout << src[i]; } cout << endl; ///结束 return 0; }