洛谷P1203 [USACO1.1] 坏掉的项链 Broken Necklace 题解

本题做法

  • 模拟,two-pointers。

思路

首先因为题目中的项链是一个环形,而在环形上面处理问题是比较麻烦的,所以我们需要将环形转化为一条直线。我们可以将整个字符串复制一遍放在末尾,然后遍历开头为 \(i=1,2,\cdots, n\) 的项链(即第 \(i\sim i+n-1\) 个珠子)就可以做到遍历每一种分割情况的效果了。

这里考虑直接用 two-pointers 模拟就行了,从开头和结尾分别遍历一遍记录答案,最后输出答案与 \(n\) 取最小值即可了(因为可能从开头结尾同时贪心会有重复记录珠子的情况,所以需要取最小值)。

代码

#include<bits/stdc++.h>

using namespace std;

typedef long long          ll;
typedef unsigned long long ull;

int n;
string str;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin>>n>>str;
    str=str+str;
    str=" "+str;
    int ans=0;
    for(int i=1;i<=n;i++){
        int left=0,right=0;
        char lz,rz;
        if(str[i]=='w') {
            int t=i;
            while(str[t]=='w') t++;
            lz=str[t];
        }
        else lz=str[i];
        if(str[i+n-1]=='w') {
            int t=i+n-1;
            while(str[t]=='w') t--;
            rz=str[t];
        }
        else rz=str[i+n-1];
        for(int j=i;j<=i+n-1&&(str[j]==lz||str[j]=='w');j++) left++;
        for(int j=i+n-1;j>=i&&(str[j]==rz||str[j]=='w');j--) right++;
        ans=max(ans,min(n,left+right));
    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2025-08-28 14:47  2789617221guo  阅读(15)  评论(0)    收藏  举报