usaco1.1.4 Broken Necklace 题解

【算法】模拟  【难度】★☆☆☆☆


仍然是模拟,但要注意这个项链是环状的。有一种比较先进的办法是把这个项链载入两次,这样就可以从头到尾遍历了。注意白色的珠子不能作为起点。
我的程序没有用上面的方法,直接遍历到最后在返回开头。
View Code
 1 /*
2 ID: wsc5001
3 LANG: C
4 TASK: beads
5 */
6 #include<stdio.h>
7 #include <stdlib.h>
8 char ch[351];
9 int n;
10 int zhaoqian(int st)
11 {
12 char goon;
13 int i=0,timess=0;
14 while(st+i<n && (ch[st+i]=='w') )
15 {i++;}
16 while(st+i>=n && (ch[st+i-n]=='w'))
17 {i++;}
18 goon = ch[st+i];
19 i=0;
20 while(st+i<n && (ch[st+i]==goon||ch[st+i]=='w'))
21 {timess++; i++;}
22 while(st+i>=n && (ch[st+i-n]==goon||ch[st+i-n]=='w'))
23 {timess++; i++;}
24 return timess;
25 }
26 int zhaohou(int st)
27 {
28 char goon;
29 int i=0,timess=0;
30 while(st-i>=0 && (ch[st-i]=='w'))
31 {i++;}
32 while(st-i<0 && (ch[st-i+n]=='w'))
33 {i++;}
34 goon = ch[st-i];
35 i=0;
36 while( st-i>=0 && (ch[st-i]==goon||ch[st-i]=='w') )
37 {timess++; i++;}
38 while(st-i<0 && (ch[st-i+n]==goon||ch[st-i+n]=='w'))
39 {timess++; i++;}
40 return timess;
41 }
42 int main()
43 {
44 FILE *fin,*fout;
45 fin=fopen("beads.in","r");
46 fout=fopen("beads.out","w");
47 int nfront=0,nback=0,max=0;
48 int i,j,flag;
49 //读入
50 fscanf(fin,"%d%s",&n,ch);
51 flag=0;
52 for (i=0;i<n;i++)
53 if(ch[i]!=ch[0]&&ch[i]!='w')
54 {flag=1;break;}
55 if (flag==0)
56 {fprintf(fout,"%d\n",n);}
57 else
58 {
59 for (i=0;i<n;i++)
60 {
61 nfront=zhaoqian(i+1);
62 nback=zhaohou(i);
63 if (nfront+nback>max)
64 max=nfront+nback;
65 if (max>n)
66 max=n;
67 }
68 fprintf(fout,"%d\n",max);
69 }
70 fclose(fin);
71 fclose(fout);
72 //system("pause");
73 }


你可能感兴趣的:(USACO)