CF2156B Strange Machine 题解
jsntzth666 · · 题解
CF2156B 题解
洛谷题目传送门
CodeForces 题目传送门
第一步理解题意
本题包含多组测试数据。
单组数据如下:
给你一个长度为
第二步做法
我们先想模拟,我们模拟这个过程,显然会 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 的数据其实是
只要字符串
那么我们就好办了,我们直接特判掉这种情况就对了。
如果字符串
第三步代码
:::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 润色文章。 :::