题目
题目来源:(校选拔)
NTU_ACM-2021新生预选赛2 - Virtual Judgehttps://vjudge.net/contest/462138#problem/ZProblem - B - Codeforceshttps://codeforces.com/contest/1271/problem/B
解析
感谢这篇文章的思路与代码提供
B. Blocks-------思维+贪心(稍思维)_AKone123456的博客-CSDN博客There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.You may perform the following operation zero or more times: choose two adj...https://blog.csdn.net/qq_43690454/article/details/104093824?ops_request_misc=&request_id=&biz_id=102&utm_term=There%20are%20nn%20blocks%20arranged%20i&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-2-104093824.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187我们可以采取贪心的思想,首先认为方块可以全部变成白色,这样在第一次遍历中将遇到黑色的方块就翻转一次,到最后后变成n-1个W+B/W,如果最后一个方块黑色,我们再从头进行一次翻转,认为全部可以翻成黑色,此时如果n-1为偶数的话则可以反转,n-1为奇数的话则输出-1
ac源代码
const int N = 1e5 + 1000;
int n;
int path[N];
vector<int> v;
char s[N];
int tot;
int main()
{
cin >> n;
cin >> (s + 1);
//假设全白
for (int i = 1; i < n; i++)
{
if (s[i] == 'B')
{
s[i] = 'W';
s[i + 1] = s[i + 1] == 'W' ? 'B' : 'W';
v.push_back(i);
}
}
if (s[n] == 'W')
{
cout << v.size() << endl;
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << endl;
return 0;
}
//假设全黑
for (int i = 1; i < n; i++)
{
if (s[i] == 'W')
{
s[i] = 'B';
s[i + 1] = s[i + 1] == 'W' ? 'B' : 'W';
v.push_back(i);
}
}
if (s[n] == 'B')
{
cout << v.size() << endl;
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << endl;
return 0;
}
cout << -1 << endl;
return 0;
}