「日常訓練」「小專題·USACO」 Broken Necklace(1-2)

題意

圓形鏈條,打斷一處可以形成一條鏈。問在哪個地方開始打斷,能夠形成最大的連續顏色(白色視作同樣的顏色)?

分析

說起來很高級,但是我們實際上並不需要窮舉打斷的地方,只需要把串重複三回啊三回。然後從第二個串的左邊開始循環找連續顏色的“初始色”(如果是白色,那麼左右看看),在初始色的左右找相同。可以看出共有n個初始色的位置,所以算法也就是O(n2) 的複雜度。然後還有一些細節要處理。作爲一條初級題目,比較鍛鍊這個時候的萌新的代碼力。

代碼

/*
ID: samhx1
LANG: C++14
TASK: beads
*/
#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define fi first
#define se second
#define ZERO(x) memset((x), 0, sizeof(x))
#define ALL(x) (x).begin(),(x).end()
#define rep(i, a, b) for (ll i = (a); i <= (b); ++i)
#define per(i, a, b) for (ll i = (a); i >= (b); --i)
#define QUICKIO                  \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pi = pair<ll,ll>;

signed main()
{
    freopen("beads.in","r",stdin);
    freopen("beads.out","w",stdout);
    int n; string str; cin>>n>>str;
    string judgeStr=str+str+str; // damn 0
    int maxans=-1;
    for(int i=n;i!=n*2;++i)
    {
        char clr_left=judgeStr[i-1]; int cnt_left=0;

        while(clr_left=='w' && cnt_left<n) // damn 1
            clr_left=judgeStr[i-1-(++cnt_left)];
        while((judgeStr[i-1-cnt_left]==clr_left || judgeStr[i-1-cnt_left]=='w') && cnt_left<n) //damn 2
            cnt_left++;

        char clr_right=judgeStr[i]; int cnt_right=0;
        while(clr_right=='w' && cnt_right+cnt_left<n)
            clr_right=judgeStr[i+(++cnt_right)];
        while((judgeStr[i+cnt_right]==clr_right || judgeStr[i+cnt_right]=='w') &&
        cnt_left+cnt_right<n)
            cnt_right++;
        //cout<<i-n<<" "<<cnt_left<<" "<<cnt_right<<endl;
        maxans=max(maxans,cnt_left+cnt_right);
    }
    cout<<maxans<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章