3777. 砖块

摘要
Title: 3777. 砖块
Tag: 递推
Memory Limit: 64 MB
Time Limit: 1000 ms

Powered by:NEFU AB-IN

Link

3777. 砖块

  • 题意

    n个砖块排成一排,从左到右编号依次为 1∼n
    每个砖块要么是黑色的,要么是白色的。
    现在你可以进行以下操作若干次(可以是 0次):
    选择两个相邻的砖块,反转它们的颜色。(黑变白,白变黑)
    你的目标是通过不超过 3n次操作,将所有砖块的颜色变得一致。

  • 思路

    当遇到相邻块改变颜色的题时,就是说明了任意两个砖块可以同时调换自己的颜色
    那么就挑选偶数颜色的砖块,从前往后,每次挑选最近的两个,进行翻转即可

  • 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    #undef int

    #define SZ(X) ((int)(X).size())
    #define ALL(X) (X).begin(), (X).end()
    #define IOS \
    ios::sync_with_stdio(false); \
    cin.tie(nullptr); \
    cout.tie(nullptr)
    #define DEBUG(X) cout << #X << ": " << X << '\n'
    typedef pair<int, int> PII;

    const int N = 1e5 + 10, INF = 0x3f3f3f3f;

    void solve()
    {
    int n;
    string s;
    cin >> n >> s;
    int b = 0, w = 0;
    vector<int> bb, ww;
    for (int i = 0; i < SZ(s); ++i)
    if (s[i] == 'B')
    b++, bb.push_back(i + 1);
    else
    w++, ww.push_back(i + 1);
    if ((b & 1) && (w & 1))
    {
    cout << "-1\n";
    return;
    }
    auto f = [&](vector<int> &v) {
    vector<int> ans;
    for (int i = 0; i < SZ(v); i += 2)
    {
    int x = v[i], y = v[i + 1];
    for (int j = x; j < y; ++j)
    ans.push_back(j);
    }
    cout << SZ(ans) << '\n';
    for (auto i : ans)
    cout << i << ' ';
    if(SZ(ans)) cout << '\n';
    };
    if (!(b & 1))
    f(bb);
    else
    f(ww);
    return;
    }

    signed main()
    {
    IOS;
    int T;
    cin >> T;
    while (T--)
    solve();
    return 0;
    }
使用搜索:谷歌必应百度