天天看點

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;
}