USACO 1.3.3 Calf Flac (calfflac)

1、比较愚蠢的暴力搜索:两个指针分别从从第一个和最后一个开始,循环往中间移动,判断两个指针之间的字符串是否是回文数。重复搜索过多,导致最后一个测试数据超时:(

/* ID: gengjia1 LANG: C TASK: calfflac */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //#define NDEBUG #include <assert.h> #define MAX_LEN 20000 int count; struct str{ int len; char s[MAX_LEN + 1]; }; struct pal{ int len; int begin; int end; }; int letter(const char a) { if((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z')) return 1; return 0; } int main(void) { FILE *fin = fopen ("calfflac.in", "r"); FILE *fout = fopen ("calfflac.out", "w"); assert(fin != NULL && fout != NULL); struct str s = {0}; struct pal pa = {0}; char tmp[80] = {0}; char t[MAX_LEN] = {0}; int curlen = 0; int i, j, k, p, q; while( fgets (tmp, 80, fin) != NULL) { strcat(s.s, tmp); } s.len = strlen(s.s); for(i = 0; i < s.len; i++) { if(letter(s.s[i]) == 0) continue; for(j = s.len-1; j > i; j--) { if(letter(s.s[j]) == 0) continue; curlen = 0; for(p = i, q = j; p < q; ) { if(letter(s.s[p]) == 0) { p++; continue; } if(letter(s.s[q]) == 0) { q--; continue; } if(tolower(s.s[p]) == tolower(s.s[q])) { curlen += 2; p++; q--; } else { curlen = 0; break; } } if(p == q && letter(s.s[p]) == 1) curlen += 1; if(curlen > pa.len) { pa.len = curlen; pa.begin = i; pa.end = j; } } } fprintf(fout, "%d/n", pa.len); for(i = pa.begin; i <= pa.end; i++) { fprintf(fout, "%c", s.s[i]); } fprintf(fout, "/n"); fclose(fin); fclose(fout); exit(0); }

你可能感兴趣的:(USACO 1.3.3 Calf Flac (calfflac))