There are blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.html
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).web
You want to find a sequence of operations, such that they make all the blocks having the same color. You don’t have to minimize the number of operations, but it should not exceed . If it is impossible to find such a sequence of operations, you need to report it.app
The first line contains one integer — the number of blocks.svg
The second line contains one string s consisting of n characters, each character is either “W” or “B”. If the i-th character is “W”, then the i-th block is white. If the i-th character is “B”, then the i-th block is black.spa
If it is impossible to make all the blocks having the same color, print
.
Otherwise, print an integer
— the number of operations. Then print
integers
, where
is the position of the left block in the pair of blocks that should be affected by the
-th operation.
If there are multiple answers, print any of them.code
给定一串黑白文本,每次能够将其中相邻2个颜色翻转,求一个可行的操做序列使得操做后颜色相同。
若是不能找到输出-1orm
一开始看到
直接打了一发爆搜+记忆化,而后MLE炸到飞起……
正解是假定操做后全白,从头扫到尾一次,假定全黑,从头扫到尾一次,看看可否成功。
好比:咱们要全白,而此时颜色是 黑白黑黑黑
能够将黑视做高台阶,白视做低台阶,而后一路推过去,最后能推平就能够了。
推平位置1后,日后找到位置2,推平位置2后,2 3都平了,再日后遍历找到位置4,推平位置4后,所有推平,合法。
所以操做序列就为:1 2 4
显然这样操做只会有2种结果:全平或者最后一个不平。
全黑全白两个都扫一遍就行了,复杂度
xml
#include <cstdio> #include <cstring> using namespace std; int n,len; char all[201]; char temp[201]; int path[201]; int tot; bool checkblack() { memcpy(temp,all,sizeof(all)); tot = 0; for(int i = 1;i<len;++i) { if(temp[i] == 'W') { temp[i] = 'B'; temp[i+1] = (temp[i+1] == 'W' ? 'B' : 'W'); path[++tot] = i; } } return temp[len] == 'B'; } bool checkwhite() { memcpy(temp,all,sizeof(all)); tot = 0; for(int i = 1;i<len;++i) { if(temp[i] == 'B') { temp[i] = 'W'; temp[i+1] = (temp[i+1] == 'W' ? 'B' : 'W'); path[++tot] = i; } } return temp[len] == 'W'; } int main() { scanf("%d",&n); scanf("%s",all+1); len = strlen(all+1); if(checkblack() || checkwhite()) { printf("%d\n",tot); for(int i =1 ;i<=tot;++i) printf("%d ",path[i]); } else printf("-1"); return 0; }