题解:P12935 [NERC 2019] Balls of Buma
Chenyuze24 · · 题解
这题其实很水。
Part1 分析
我们可以用双端队列来维护字符串,令其为
deque<char> q(str.begin(),str.end());
考虑如果它能让所有球被消除需要什么。
- 中间的字符出现的连续数量肯定要比
2 大,这样才能加入一个字符后消掉它。 - 若不管出现数量,两端的字符必须回文,比如
\text{AAABBBCCBAA} ,称为字符回文。 - 回文的前后两段字符个数的总数量必须要严格比
2 大。
那么有了这些要求后,就可以写了。首先保证它是字符回文的,那么第一个元素要和最后一个相等。那么我们记 q.front()。那么我们需要保证它是字符回文的,因而分别从前,后两端删去
while (!q.empty() && q.front() == c) {
q.pop_front();
ans++;
}
while (!q.empty() && q.back() == c) {
q.pop_back();
ans++;
}
我们需要保证
Part2 细节
- 每次
ans 要初始化。 - 每次的循环都是在
q 非空这个条件下执行的。Part3 代码
#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;
}