问题:
http://ace.delos.com/usacoprob2?a=NAqufR1Vt6H&S=calfflac思路:
不是很难,枚举,但需要注意很多细节
另外,要注意存在奇数与偶数长度的回文这两种情况
完全参考ANALYSIS,学习到很多纯指针操作字符串的写法
代码:
1 /*
2 ID: simplyz2
3 LANG: C
4 TASK: calfflac
5 */
6 #include<stdio.h>
7 #include<stdlib.h>
8 #include<string.h>
9 #include<assert.h> /* void assert(int exp); */
10 #include<ctype.h>
11 #define MAX_LEN 21000
12 char text[MAX_LEN], fulltext[MAX_LEN];
13 char *pal;
14 int pallen;
15
16 void
17 solve()
18 {
19 int len;
20 char *fwd, *bkwd, *end, *p;
21 pallen = 0;
22 end = text + strlen(text);
23 for(p=text; *p; p++) {
24 for(fwd=p, bkwd=p; fwd<end && bkwd>=text && *fwd==*bkwd; fwd++, bkwd--); /* odd: middle, such as 'aba' */
25 bkwd++;
26 len = fwd - bkwd;
27 if(len > pallen) {
28 pallen = len;
29 pal = bkwd;
30 }
31 for(fwd=p+1, bkwd=p; fwd<end && bkwd>=text && *fwd==*bkwd; fwd++, bkwd--); /* even: left middle, such as 'abba' */
32 bkwd++;
33 len = fwd - bkwd;
34 if(len > pallen) {
35 pallen = len;
36 pal = bkwd;
37 }
38 }
39 }
40
41 void
42 output()
43 {
44 int i, n;
45 char *p;
46 n = pal - text;
47 printf("%d\n", pallen);
48 for(i=0, p=fulltext; *p; p++) {
49 if(isalpha(*p))
50 ++i;
51 if(i > n)
52 break;
53 }
54 for(i=0; i<pallen && *p; p++) {
55 fputc(*p, stdout);
56 if(isalpha(*p))
57 ++i;
58 }
59 printf("\n");
60 }
61
62 int
63 main(int argc, char **argv)
64 {
65 char *p, *q;
66 int c;
67 freopen("calfflac.in", "r", stdin);
68 freopen("calfflac.out", "w", stdout);
69 p = fulltext;
70 q = text;
71 while((c=getc(stdin)) != EOF) { /* operation on each char */
72 if(isalpha(c))
73 *q++ = tolower(c);
74 /* '++''s priority is higher than '*', and '++' first return 'p', than move the pointer forward */
75 *p++ = c;
76 }
77 *p = '\0';
78 *q = '\0';
79 solve();
80 output();
81 return 0;
82 }