#include <stdio.h>
void main ()
{
FILE *fin = fopen ("beads.in", "r");
FILE *fout = fopen ("beads.out", "w");
int i,nCount,Max=0;
char beads[400],tempbead;
fscanf (fin, "%d\n%s", &nCount,beads);
for(i=0;i<nCount;i++)
{
int j,k,temp=0;
tempbead=beads[i];
j=i;
while((beads[j]==tempbead||beads[j]=='w'||(beads[i]=='w'&&tempbead=='w'))&&temp<nCount)
{
temp++;
tempbead=beads[j]=='w'?tempbead:beads[j];
j=j+1<nCount?j+1:j+1-nCount;
}
k=i-1<0?nCount-i-1:i-1;
tempbead=beads[k];
j=k;
while((beads[j]==tempbead||beads[j]=='w')&&temp<nCount)
{
temp++;
tempbead=beads[j]=='w'?tempbead:beads[j];
j=j-1<0?nCount-j-1:j-1;
}
if(temp>Max)
Max=temp;
}
fprintf (fout, "%d\n",Max);
exit (0);
}
用一个数组beads存储整个项链,再从头开始逐个向前向后搜索,复杂度是O(n^2),网上有人说用动态规划可以将复杂度降到O(n),但对动态规划还不是很理解,留待今后学习。代码比较丑陋,中间考虑了很多种情况。比如第一个while循环条件是当前珠子如果等于上一个非w的珠子(tempbead),或当前珠子是w,或第一个珠子是w且还没出现第一个不是w的珠子的时候执行,同时防止全是一种珠子的情况发生,temp要小于珠子总数。如果当前珠子是不是w,则记录在tempbead中,这样w后第一个不是tempbead的珠子不会被收集。对于j+1、j-1的判断以及相应对j的赋值是构成循环的主要步骤。