AcWing_3777 砖块(递推)

AcWing

3777. 砖块

递推。对于最终字符串的状态,只可能是全'W'或者全'B'. 对于某一连续的砖块对,其要么更新,要么保持不变。选择某一种最终颜色,从字符串的首个位置开始遍历:对于第1个位置,只能更新/保持第1个砖块对,使得第1个位置的颜色为目标颜色;对于第2个位置,只能更新/保持第2个砖块对(不能更新第1个砖块对,因为第1个位置的颜色已经确定),使得第2个位置的颜色为目标颜色,…,对于第n - 1个位置,只能更新/保持第n - 1个砖块对(也是最后一个砖块对),使得第n - 1个位置的颜色为目标颜色。此后,如果最后一个砖块的颜色为目标颜色,那么可以达到目的;否则不能。

#include <bits/stdc++.h>
using namespace std;
// 递推
int t, n;
void update(char& c){
    if(c == 'W') c = 'B';
    else c = 'W';
}
bool check(char c, string str){
    vector<int> arr;
    for(int i = 0; i <= n - 2; i++){
        if(str[i] != c){
            update(str[i]);
            update(str[i + 1]);
            arr.push_back(i);
        }
    }
    if(str[n - 1] != c) return false;
    else{
        cout << (int)arr.size() << endl;
        for(int i = 0; i <= (int)arr.size() - 1; i++) cout << arr[i] + 1 << " \n"[i == (int)arr.size() - 1];
        return true;
    }
}
int main(){
    cin >> t;
    while(t--){
        cin >> n;
        string str;
        cin >> str;
        if(!check('W', str) && !check('B', str)) cout << "-1" << endl;
    }
    return 0;
}