题解:P12935 [NERC 2019] Balls of Buma

· · 题解

这题其实很水。

Part1 分析

我们可以用双端队列来维护字符串,令其为 q。

deque<char> q(str.begin(),str.end());

考虑如果它能让所有球被消除需要什么。

那么有了这些要求后,就可以写了。首先保证它是字符回文的,那么第一个元素要和最后一个相等。那么我们记 c 为 q.front()。那么我们需要保证它是字符回文的,因而分别从前,后两端删去 c,用 ans 去记录 c 在这两段中出现的次数。

while (!q.empty() && q.front() == c) {
    q.pop_front();
    ans++;
}
while (!q.empty() && q.back() == c) {
    q.pop_back();
    ans++;
}

我们需要保证 ans>2,则当 ans<3 时就可以退出了。如果 q 已经空了,那么就直接输出 ans+1 即可,就是说中间的 ans 个字符有 ans+1 个空隙能插入(包括两端)。最后如果什么都没输出过的话,就在最后输出 0 即可,代表无法让所有球都被消除。

Part2 细节

#include<bits/stdc++.h>//万能头。
using namespace std;
string str;
void read(){//读入。
    cin>>str;
}
void solve()
{
    deque<char> q(str.begin(),str.end());//双端队列。
    while (!q.empty() && q.front() == q.back()) {//必须q非空。
        char c = q.front();//取出队首。
        int ans = 0;
        while (!q.empty() && q.front() == c) {
            q.pop_front();//记得弹出。
            ans++;
        }
        while (!q.empty() && q.back() == c) {//与上同理。
            q.pop_back();
            ans++;
        }
        if (q.empty() && ans >= 2) {//直接输出。
            cout <<ans+1<<'\n';
            return;
        }
        if (ans < 3) {
            break;//退出。
        }
    }
    cout << 0 ;
}
int main()
{
    read();
    solve();
    return 0;
}