[Codeforces #608 div2]1272B Blocks

Description

There are n n 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 3 n 3⋅n . If it is impossible to find such a sequence of operations, you need to report it.app

Input

The first line contains one integer n ( 2 n 200 ) n(2≤n≤200) — 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

Output

If it is impossible to make all the blocks having the same color, print 1 −1 .
Otherwise, print an integer k ( 0 k 3 n ) k(0≤k≤3⋅n) — the number of operations. Then print k k integers p 1 , p 2 , , p k ( 1 p j n 1 ) p_1,p_2,…,p_k (1≤p_j≤n−1) , where p j p_j is the position of the left block in the pair of blocks that should be affected by the j j -th operation.
If there are multiple answers, print any of them.code

題意

給定一串黑白文本,每次能夠將其中相鄰2個顏色翻轉,求一個可行的操做序列使得操做後顏色相同。
若是不能找到輸出-1orm

思路

一開始看到 n < = 200 n<=200 直接打了一發爆搜+記憶化,而後MLE炸到飛起……
正解是假定操做後全白,從頭掃到尾一次,假定全黑,從頭掃到尾一次,看看可否成功。
好比:咱們要全白,而此時顏色是 黑白黑黑黑
能夠將黑視做高臺階,白視做低臺階,而後一路推過去,最後能推平就能夠了。
例子
推平位置1後,日後找到位置2,推平位置2後,2 3都平了,再日後遍歷找到位置4,推平位置4後,所有推平,合法。
所以操做序列就爲:1 2 4
顯然這樣操做只會有2種結果:全平或者最後一個不平。
全黑全白兩個都掃一遍就行了,複雜度 O ( n ) O(n) xml

Code

#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;
}
相關文章
相關標籤/搜索