#include <bits/stdc++.h>
#define FOR(i, beg, ed, etr) for(ll i = beg;i <= ed;i += etr)
#define FORN(i, beg, ed, etr) for(ll i = beg;i >= ed;i -= etr)
#define all(x) x.begin(), x.end()
#define F first
#define pb push_back
#define S second
#define con continue
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pii;
typedef pair<ll,ll> pll;
typedef double db;
typedef long double ld;
//qwertqetqer
const ll inf = 1e9;
const ll INF = 1e18;
const ll N = 5e5 + 5;
const ll MOD = 1e9 + 7;
ll a[N],pre[N];
int n;
struct node{
ll pre,suf,sum,ans;
node operator+(node b){
node ret;
ret.pre = max(pre, sum + b.pre);
ret.suf = max(suf + b.sum, b.suf);
ret.sum = sum + b.sum;
ret.ans = max(max(ans+b.sum, sum + b.ans), pre + b.suf);
return ret;
}
};
node t[4 * N];
void build(int v = 1,int l = 1,int r = n){
if(l == r){
if(a[l] == 1)t[v] = {1,1,1,1};
else t[v] = {0,0,-1,0};
return;
}
int mid = (l + r) / 2;
build(v+v,l,mid);
build(v+v+1,mid+1,r);
t[v] = (t[v+v] + t[v+v+1]);
}
node get(int ql,int qr,int v = 1,int l = 1,int r= n){
if(ql <= l && r <= qr){
return t[v];
}
if(r < ql || qr < l)return {0,0,0,0};
int mid = (l + r) / 2;
return (get(ql,qr,v+v,l,mid) + get(ql,qr,v+v+1,mid+1,r));
};
void solve(){
cin >> n;
FOR(i, 1, n, 1){
char c;cin >> c;
if(c == 'C')a[i] = -1;
else a[i] = 1;
pre[i] = pre[i-1] + a[i];
}
build();
int q;cin >> q;
while(q--){
int l,r;cin >> l >> r;
node res = get(l,r);
cout << res.ans << '\n';
}
}
main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
// freopen("optmilk.in","r",stdin);
// freopen("optmilk.out","w",stdout);
ll abd = 1;
// cin >> abd;
FOR(i, 1, abd, 1){
solve();
}
}
Compilation message (stderr)
election.cpp:70:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
70 | main(){
| ^~~~| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |