跳到正文

题解

CF2156B Strange Machine 题解

jsntzth666约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年8月12日
收录
2026年8月12日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
1
题目
CF2156B

版本

  1. v1当前

CF2156B 题解

洛谷题目传送门

CodeForces 题目传送门

第一步理解题意

本题包含多组测试数据。

单组数据如下:

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

第二步做法

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

会 TLE 的代码
C++
#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 的数据其实是 ss 每个字符都是 A\mathtt{A}。

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

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

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

第三步代码

完整代码(码风较丑勿喷)
C++
#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;
}

后记

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

AI 使用说明

使用 DeepSeek 润色文章。