1、串联两条链解开环形 2、暴力搜索 3、注意边界条件 3 rrr 易出错! /* ID: gengjia1 LANG: C TASK: beads */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> int main(void) { FILE *fin = fopen ("beads.in", "r"); FILE *fout = fopen ("beads.out", "w"); int N, n = 0; char *s = NULL, *st = NULL; int fh = 0, sh = 0; //first half, second half char fc, lc, cc; //first half char, last char, current char int i, j; fscanf (fin, "%d", &N); assert(N >= 3); assert(N <= 350); s = (char *)malloc(2 * N + 1); st = (char *)malloc(N+1); if( s == NULL || st == NULL) exit(1); fscanf (fin, "%s", st); assert(strlen(st) == N); s = strcpy(s, st); s = strcat(s, st); for(i=0; i < N; i++) { fh = 0; sh = 0; j = 0; fc = lc = s[i]; fh += 1; j = i + 1; cc = s[j]; while( !(sh > 0 && cc == fc) ) //前半段字符第二次出现相等 { if(cc == lc) { if(sh == 0) { if(fh >= N) { break; } fh += 1; } else { sh +=1; } } else { if(fc == lc) { if(fc == 'w') { fh += 1; fc = cc; } else if(cc =='w') { fh += 1; } else { sh += 1; } } else { if(fc == cc) { fh += 1; } else { sh += 1; } } lc = cc; } j += 1; cc = s[j]; } if (n < fh + sh) { n = fh + sh; } if (n == N) { break; //注意边界条件 } } fprintf (fout, "%d/n", n); free(s); fclose(fin); fclose(fout); exit(0); }