3777. 砖块
-
题目描述
-
思路
- 那么我们可以假定,最后全部反转成白色或者黑色,我们只需要比较每个砖块与我们的目标是否一致,假如,我们想让最后的颜色统一为白色,如果当前的砖块的颜色不是白色,我们便反转一次。例如:下标为0的砖块(也就是第一个)是黑色,但我们目标是白色,那么便翻转一次,而且每一个砖块只能翻转一次,只要翻转就不能再翻了,这样一来,我们现在只用管剩下的n-1个,
- 同理,我们再看下标为1的砖块是否为黑色,如果不是就翻转一次…一直反转到最后一个,当全部翻转之后,我们判断一下最后一个砖块是否为目标颜色,如果不是则证明不能反转为此颜色,我们再来判断另一种,另一种同理。
-
代码
-
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<vector> using namespace std; int n; string str; void update(char& c){ if(c == 'W') c = 'B'; else c = 'W'; } bool check(char c){ vector<int> res; string s = str; for(int i = 0 ; i + 1 < n ; i++){ if(s[i] != c){ update(s[i]); update(s[i + 1]); // 记录被改变的索引 res.push_back(i); } } //判断字符串s的最后一个字母是否是我们想要的那个字母 if(s.back() != c ) return false; // 输出操作次数 cout << res.size() << endl; //注意位置是下标加1 因为题目的编号是从1 开始的 for(int x : res) cout << x + 1 << ' '; if(res.size()) cout << endl; return true; } int main(){ int T; cin >> T; while(T--){ cin >> n >> str; if(!check('B') && !check('W')) puts("-1"); } return 0 ; }
-