#include <bits/stdc++.h>
using namespace std;
#define mat array<array<int, 3>, 3>
#define _(i, j) max({a[i][0] + b[0][j], a[i][1] + b[1][j], a[i][2] + b[2][j]})
mat operator* (mat a, mat b) {
return {_(0, 0), _(0, 1), _(0, 2),
_(1, 0), _(1, 1), _(1, 2),
_(2, 0), _(2, 1), _(2, 2)};
}
const int maxn = 500005, inf = 1 << 30;
int n, q;
string s;
mat val[maxn][20];
int pref[maxn];
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
cin >> n >> s >> q;
s = ' ' + s;
for (int i = 1; i <= n; i ++) {
val[i][0] = {s[i] == 'C' ? 1 : -1, 0, -inf, -inf, 0, -inf, 0, -inf, 0};
pref[i] = pref[i - 1] + (s[i] == 'C');
}
for (int j = 1; j <= __lg(n); j ++)
for (int i = 1; i + (1 << j) - 1 <= n; i ++)
val[i][j] = val[i][j - 1] * val[i + (1 << j - 1)][j - 1];
while (q -- ) {
int l, r;
cin >> l >> r;
mat ans = {0, 0, 0, -inf, -inf, -inf, -inf, -inf, -inf};
int u = l;
for (int i = __lg(n); i >= 0; i -- )
if (u + (1 << i) <= r + 1) ans = ans * val[u][i], u += (1 << i);
int sum = ans[0][0], mx = max(ans[0][1], sum), res = 2 * (pref[r] - pref[l - 1]) - sum;
cout << r - l + 1 - (res - mx + sum) << endl;
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |