您的位置:首页 > 其它

USACO Section 1.3: Calf Flac

2014-03-20 11:42 267 查看
这题做了很久,一开始用了dp的方法,结果超时,后来用了现在的法子,还有一些细节需要注意,一个是string里不都是字母,另一个是输出的时候要在原来的字符串那里换行,这里用了set来记录换行位置,可能有更好的方法

/*
ID: leetcod3
PROG: calfflac
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <queue>
#include <cstring>
#include <cmath>
#include <list>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <stack>

using namespace std;

ofstream fout ("calfflac.out");
ifstream fin ("calfflac.in");

int main() {
string s1, s;
set<int> newline;
while (getline(fin, s1)) {
s += s1;
newline.insert(s.size());
}
s1 = "";
int len = 1;
int l, r;
//cout << s << endl;
for (int i = 0; i < s.size(); i++) {
int left, right;
left = right = i;
int lentmp = -1;
while (left >= 0 && right < s.size()) {
if (!isalpha(s[left])) {
left--;
continue;
}
if (!isalpha(s[right])) {
right++;
continue;
}
if (tolower(s[left]) == tolower(s[right])) {
left--;
right++;
lentmp += 2;
}
else break;
}
left++, right--;
while (left < s.size() && !isalpha(s[left])) left++;
while (right >= 0 && !isalpha(s[right])) right--;
if (lentmp > len) {
len = lentmp;
l = left;
r = right;
}
left = i;
right = i + 1;
lentmp = 0;
while (left >= 0 && right < s.size()) {
if (!isalpha(s[left])) {
left--;
continue;
}
if (!isalpha(s[right])) {
right++;
continue;
}
if (tolower(s[left]) == tolower(s[right])) {
left--;
right++;
lentmp += 2;
}
else break;
}
left++, right--;
while (left < s.size() && !isalpha(s[left])) left++;
while (right >= 0 && !isalpha(s[right])) right--;
if (lentmp > len) {
len = lentmp;
l = left;
r = right;
}
}
fout << len << endl;
//cout << l << " " << r << endl;
for (int i = l; i <= r; i++) {
if (newline.find(i) != newline.end()) fout << endl;
fout << s[i];
}
fout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: