P1203 [USACO1.1] 坏掉的项链 Broken Necklace(模拟)

简介: 算法

题意:

5.png

图片 A 中的项链可以用下面的字符串表示:

brbrrrbbbrrrrrbrrbbrbbbbrrrrb

假如你要在一些点打破项链,展开成一条直线,然后从一端开始收集同颜色的珠子直到你遇到一个不同的颜色珠子,在另一端做同样的事(颜色可能与在这之前收集的不同)。 确定应该在哪里打破项链来收集到最大数目的珠子。

思路:

看是dp,但是实际上可以当做模拟题做,暴力的枚举断点,然后模拟往左找,往右找,输出最大的值,但是由于有个万能的w,处理的十分麻烦,这里有给很清晰的代码,贴贴

#include<bits/stdc++.h>
using namespace std;
string a;
int f(int x)
{
    int s=0;
    char a1=a[x];
    char b2=a[x+1];
    for(int i=x;;i--)//往前看和往后看
    {
        if(a[i]==a1)s++;
        else if(a[i]=='w')
            s++;
        else
            break;
    }
    for(int i=x+1;;i++)
    {
        if(a[i]==b2)s++;
        else if(a[i]=='w')
            s++;
        else
            break;
    }
    return s;
}
int main()
{
    int ans,n;
    ans=-1;
    cin>>n;cin>>a;
    a=a+a+a;
    for(int i=n;i<2*n;i++)//三段 从中间那一段开始处理
    {
        if(a[i]==a[i+1])
            continue;
        if(a[i]=='w')//这TMD硬是看的到第三个点 要不然真不会
        {
            a[i]='r';
            ans=max(ans,f(i));
            a[i]='b';
            ans=max(ans,f(i));
            a[i]='w';
        }
        ans=max(ans,f(i));
    }
    ans=min(ans,n);//最长也不能比总长长
    if(ans==-1)ans=n;//出现这种情况必定是一路continue过来的
    cout<<ans<<endl;
    return 0;
}
相关文章
|
C++
【PAT甲级 - C++题解】1084 Broken Keyboard
【PAT甲级 - C++题解】1084 Broken Keyboard
67 0
|
机器学习/深度学习 算法 C++
图像去雨(rainy streaks removal)#(代码+毕设)
图像去雨(rainy streaks removal)#(代码+毕设)
|
人工智能 BI
[UVA 1599] Ideal Path | 细节最短路
Description New labyrinth attraction is open in New Lostland amusement park. The labyrinth consists of n rooms connected by m passages. Each passage is colored into some color ci .
213 0
|
算法 Python
动态规划法(六)鸡蛋掉落问题(一)(egg dropping problem)
  继续讲故事~~   这天,丁丁正走在路上,欣赏着路边迷人的城市风景,突然发现前面的大楼前围了一波吃瓜群众。他好奇地凑上前去,想一探究竟,看看到底发生了什么事情。
1978 0
[LintCode] Trapping Rain Water 收集雨水
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
1132 0
|
vr&ar Python
Codeforces 842A Kirill And The Game【暴力,水】
A. Kirill And The Game time limit per test:2 seconds memory limit per test:256 megabytes input:standard input output:standard output Kirill plays a new computer game.
1304 0