#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, m;
string s;
mat tr[maxn * 4];
int pref[maxn];
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
cin >> n >> s >> q;
s = ' ' + s, m = (1 << __lg(n) + 1) - 1;
for (int i = 1; i <= n; i ++) {
tr[i + m] = {s[i] == 'C' ? 1 : -1, 0, -inf, -inf, 0, -inf, 0, -inf, 0};
pref[i] = pref[i - 1] + (s[i] == 'C');
}
for (int i = m; i >= 1; i -- )
tr[i] = tr[i << 1] * tr[i << 1 | 1];
while (q -- ) {
int l, r;
cin >> l >> r;
int L = l + m, R = r + m;
mat P = {0, 0, 0, -inf, -inf, -inf, -inf, -inf, -inf}, Q = {0, 0, 0, 0, 0, 0, 0, 0, 0};
for (; L <= R; L >>= 1, R >>= 1) {
if (L & 1) P = P * tr[L ++];
if (~R & 1) Q = tr[R --] * Q;
}
mat ans = P * Q;
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... |