usaco1.1.4 Broken Necklace破碎的项链

本文介绍了USACO比赛中的题目“破碎的项链”,这是一道涉及环状序列遍历的模拟问题。文章通过两种方法——找前缀和找后缀——来计算项链中最大颜色连续段的长度,并提供了C语言的解决方案。
usaco1.1.4 beads
Broken Necklace破碎的项链

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



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值