USACO Broken Necklace

按题目给的tips,s+=s;之后从头开始遍历,找到所有的r...w...b结构,记录首尾两个offset然后向左右遍历,遇到w或者与对应的offset处一样的话长度就++;


坑:
最后结果如果大于n说明有重复
如果为0说明全为w

防止漏掉结尾一段,手动给结尾处一个断


代码:
变量解释:

n长度;s字符串;tc储存遍历时当前的颜色;of1,of2前后两个偏移;tof1,tof2临时;almax最长长度;tmax临时长度;

/*
ID: windroid
LANG: C++
TASK: beads
*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
    ifstream fin("beads.in");
    ofstream fout("beads.out");
    int n;
    string s;
    fin>>n>>s;
    //cin>>s;
    s+=s;
    char tc=0;
    int of1=0,of2=0;
    int almax=0;
    for(int i=0;i<2*n;i++){
        if(tc==0&&s[i]!='w'){
            tc=s[i];
            of1=i;
        }
        if(s[i]!='w'&&s[i]!=tc||i==2*n-1){
           // cout<<"|"<<i<<"|";
            //cout<<"|";
            if(of2!=0){
                of1=of2;
            }
            tc=s[i];
            of2=i;
            int tmax=of2-of1+1;
            int tof1=of1,tof2=of2;
            while(tof1>0&&(s[tof1-1]=='w'||s[tof1-1]==s[of1])){
                tmax++;
                tof1--;
            }
            while(tof2<2*n-1&&(s[tof2+1]=='w'||s[tof2+1]==s[of2])){
                tmax++;
                tof2++;
            }
           // if(tmax==73) cout<<tof1<<"=="<<tof2<<endl;
            if(tmax>almax){
                almax=tmax;
            }
        }
       // cout<<s[i];
    }
    //cout<<endl<<almax<<endl;
    if(almax==0||almax>=n) almax=n;
    fout<<almax<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值