您的位置:首页 > 其它

usaco1.1.4 Broken Necklace 题解

2012-01-10 21:47 399 查看

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

仍然是模拟,但要注意这个项链是环状的。有一种比较先进的办法是把这个项链载入两次,这样就可以从头到尾遍历了。注意白色的珠子不能作为起点。
我的程序没有用上面的方法,直接遍历到最后在返回开头。
View Code

/*
ID: wsc5001
LANG: C
TASK: beads
*/
#include<stdio.h>
#include <stdlib.h>
char ch[351];
int n;
int zhaoqian(int st)
{
char goon;
int i=0,timess=0;
while(st+i<n && (ch[st+i]=='w') )
{i++;}
while(st+i>=n && (ch[st+i-n]=='w'))
{i++;}
goon = ch[st+i];
i=0;
while(st+i<n && (ch[st+i]==goon||ch[st+i]=='w'))
{timess++; i++;}
while(st+i>=n && (ch[st+i-n]==goon||ch[st+i-n]=='w'))
{timess++; i++;}
return timess;
}
int zhaohou(int st)
{
char goon;
int i=0,timess=0;
while(st-i>=0 && (ch[st-i]=='w'))
{i++;}
while(st-i<0 && (ch[st-i+n]=='w'))
{i++;}
goon = ch[st-i];
i=0;
while( st-i>=0 && (ch[st-i]==goon||ch[st-i]=='w') )
{timess++; i++;}
while(st-i<0 && (ch[st-i+n]==goon||ch[st-i+n]=='w'))
{timess++; i++;}
return timess;
}
int main()
{
FILE *fin,*fout;
fin=fopen("beads.in","r");
fout=fopen("beads.out","w");
int nfront=0,nback=0,max=0;
int i,j,flag;
//读入
fscanf(fin,"%d%s",&n,ch);
flag=0;
for (i=0;i<n;i++)
if(ch[i]!=ch[0]&&ch[i]!='w')
{flag=1;break;}
if (flag==0)
{fprintf(fout,"%d\n",n);}
else
{
for (i=0;i<n;i++)
{
nfront=zhaoqian(i+1);
nback=zhaohou(i);
if (nfront+nback>max)
max=nfront+nback;
if (max>n)
max=n;
}
fprintf(fout,"%d\n",max);
}
fclose(fin);
fclose(fout);
//system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: