EOJ1854 Broken Necklace 枚举

本文介绍了一种针对特定项链结构的搜索算法,该算法通过枚举所有可能的断点来找出最长的可移除珠串长度。对于每一种断点情况,算法分别从两侧进行颜色匹配,考虑白色珠子的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意就是一个项链从某一个位置断开,从断开的两段开始搜索,同样颜色的珠子可以取下来,其中白色可以看成红色或者蓝色。因为数据量少,可以枚举每一个点作为断点,算出答案。具体代码如下:

#include <iostream>
#include <set>
#include <cstdlib>
#include <cstdio>
#include <utility>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#define maxn 10000+5
#define INF 0x3fffff

using namespace std;

typedef long long LL;
typedef pair<int, int> pii;
map<pii, int> M;
int vis[maxn];//判断某一个位置是否搜索过
             //是为了防止这种情况wwrr dd,这个ww可能被搜索两次
int cal(string necklace, int break_point)
{
    int len = necklace.length();
    int i = break_point;
    int j = (break_point + 1) % len;
    int cnt1 = 0, cnt2 = 0;
    char flag = '\0';
    int ok = 0;
    //在搜索rrww bbb这种情况时,从w开始往左边搜索,刚开始颜色还未确定
    //所以用一个不会出现的字符flag = '\0'来表示当前颜色,等搜索到r的时候,颜色就确定了
    //flag就变成了r
    while ((flag == '\0' || necklace[i] == flag || necklace[i] == 'w')&& !vis[i])
    {
        if (!ok && necklace[i] != 'w')
        {
            flag = necklace[i];
            ok = 1;
        }
        cnt1++;
        vis[i] = 1;
        i = (i - 1 + len) % len;//项链是循环的,所以用%
    }
    flag = '\0';
    ok = 0;
    while ((flag == '\0' || necklace[j] == flag || necklace[j] == 'w')&& !vis[j])
    {
        if (!ok && necklace[j] != 'w')
        {
            flag = necklace[j];
            ok = 1;
        }
        cnt2++;
        vis[j] = 1;
        j = (j + 1) % len;
    }
    return cnt1 + cnt2;
}

int solve(string necklace)
{
    int len  = necklace.length();
    int ans = 0;
    for (int i = 0; i < len; i++)//对每个断点枚举
    {
        memset(vis, 0, sizeof(vis));
        ans = max(ans, cal(necklace, i));
    }
    return ans;
}

int main()
{
    //freopen("Input.txt", "r", stdin);
    int n;
    string necklace;
    scanf("%d", &n);
    cin >> necklace;
    printf("%d\n",solve(necklace));
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值