CF2156B Strange Machine 题解

· · 题解

CF2156B 题解

洛谷题目传送门

CodeForces 题目传送门

第一步理解题意

本题包含多组测试数据。

单组数据如下:

给你一个长度为 n (1 \le n \le 20) 的字符串 s。s 每个字符是 \mathtt{A} 或者 \mathtt{B}。给你 q(1 \le q \le 10^4) 次询问,每次询问给你个数 a,从字符串第一位开始往后(最后一位后面的字符是第一位),每次如果当前字符是 \mathtt{A},a := a - 1,如果当前字符是 \mathtt{B},a := \left\lfloor\frac{a}{2}\right\rfloor。

第二步做法

我们先想模拟,我们模拟这个过程,显然会 TLE。

:::info[会 TLE 的代码]

#include <bits/stdc++.h>

using namespace std;

const int N = 5e5 + 5;

int t;

int n, q, a[N];
string s;

void solve () {
    cin >> n >> q >> s;
    for (int i = 1; i <= q; i++)
        cin >> a[i];

    for (int i = 1; i <= q; i++) {
        int pos = 0, ans = 0;
        while (a[i] != 0) {
            if (s[pos] == 'A')
                a[i]--;
            else
                a[i] /= 2;
            pos++;
            if (pos == s.size ())
                pos = 0;
            ans++;
        }
        cout << ans << "\n";
    }
}

signed main () {
    ios::sync_with_stdio (0), cin.tie (0), cout.tie (0);
    cin >> t;
    while (t--)
        solve ();
    return 0;
}

:::

考虑优化。

我们思考为什么会 TLE,是什么样的数据导致的。

TLE 的数据其实是 s 每个字符都是 \mathtt{A}。

只要字符串 s 中有一个 \mathtt{B},那么每扫一轮 a 至少能少一半。那么只要字符串 s 中有 \mathtt{B},一次查询数据的时间复杂度就变成了 O(\log a) 了。

那么我们就好办了,我们直接特判掉这种情况就对了。

如果字符串 s 全是 \mathtt{A},那我们不停减一那么也就是 a 次操作,答案就是 a。

第三步代码

:::info[完整代码(码风较丑勿喷)]

#include <bits/stdc++.h>

using namespace std;

const int N = 5e5 + 5;

int t;

int n, q, a[N];
string s;

void solve () {
    cin >> n >> q >> s;

    bool b = 0;
    for (auto i : s)
        if (i == 'B') {
            b = 1;
            break;
        }

    for (int i = 1; i <= q; i++)
        cin >> a[i];

    for (int i = 1; i <= q; i++) {
        if (b == 0) {
            cout << a[i] << "\n";
            continue;
        }

        int pos = 0, ans = 0;
        while (a[i] != 0) {
            if (s[pos] == 'A')
                a[i]--;
            else
                a[i] /= 2;
            pos++;
            if (pos == s.size ())
                pos = 0;
            ans++;
        }
        cout << ans << "\n";
    }
}

signed main () {
    ios::sync_with_stdio (0), cin.tie (0), cout.tie (0);
    cin >> t;
    while (t--)
        solve ();
    return 0;
}

:::

后记

制作不易,点个关注,再点个赞吧。

:::info[AI 使用说明] 使用 DeepSeek 润色文章。 :::