CF2156B 题解
第一步理解题意
本题包含多组测试数据。
单组数据如下:
给你一个长度为 的字符串 。 每个字符是 或者 。给你 次询问,每次询问给你个数 ,从字符串第一位开始往后(最后一位后面的字符是第一位),每次如果当前字符是 ,,如果当前字符是 ,。
第二步做法
我们先想模拟,我们模拟这个过程,显然会 TLE。
会 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 的数据其实是 每个字符都是 。
只要字符串 中有一个 ,那么每扫一轮 至少能少一半。那么只要字符串 中有 ,一次查询数据的时间复杂度就变成了 了。
那么我们就好办了,我们直接特判掉这种情况就对了。
如果字符串 全是 ,那我们不停减一那么也就是 次操作,答案就是 。
第三步代码
完整代码(码风较丑勿喷)
#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 润色文章。