This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ar array
using namespace std;
typedef long double ld;
typedef long long ll;
const int inf=2e9+9;
const ll linf=4e18+18;
const int N=5e5;
struct segtr {
struct node {
int ans, ansup, ansdown;
};
string s;
vector<int> a, b;
vector<node> t;
int n;
segtr(string &s, int n): s(s), n(n) {
a.resize(n+1); a[0]=0;
b.resize(n+1); b[n]=0;
for (int i=0; i<n; ++i) a[i+1]=a[i]+(s[i]=='C'?1:-1);
for (int i=n-1; ~i; --i) b[i]=b[i+1]+(s[i]=='C'?1:-1);
t.resize(n*4);
}
void comb(int v, int l, int r) {
int m=(l+r)/2;
t[v].ans=t[2*v+1].ansup+t[2*v+2].ansdown;
int x1=max(0,t[2*v+1].ans-t[2*v+1].ansup-t[2*v+2].ansdown-(b[m]-b[r]));
int x2=max(0,t[2*v+2].ans-t[2*v+2].ansdown-t[2*v+1].ansup-(a[m]-a[l]));
t[v].ans+=max(x1,x2);
t[v].ansup=max(t[2*v+1].ansup,t[2*v+2].ansup-(a[m]-a[l]));
t[v].ansdown=max(t[2*v+1].ansdown-(b[m]-b[r]),t[2*v+2].ansdown);
}
void build(int v, int l, int r) {
if (l+1==r) {
if (s[l]=='C') t[v].ans=t[v].ansup=t[v].ansdown=0;
else t[v].ans=t[v].ansup=t[v].ansdown=1;
}
else {
int m=(l+r)/2;
build(2*v+1,l,m);
build(2*v+2,m,r);
comb(v,l,r);
}
} void build() {build(0,0,n);}
node qry(int v, int tl, int tr, int l, int r) {
if (l>=r) return {};
if (tl==l&&tr==r) return t[v];
int tm=(tl+tr)/2;
node L=qry(2*v+1,tl,tm,l,min(r,tm)), R=qry(2*v+2,tm,tr,max(l,tm),r);
if (l>=min(r,tm)) return R;
if (max(l,tm)>=r) return L;
node S={};
S.ans=L.ansup+R.ansdown;
int x1=max(0,L.ans-L.ansup-R.ansdown-(b[tm]-b[r]));
int x2=max(0,R.ans-R.ansdown-L.ansup-(a[tm]-a[l]));
S.ans+=max(x1,x2);
S.ansup=max(L.ansup,R.ansup-(a[tm]-a[l]));
S.ansdown=max(L.ansdown-(b[tm]-b[r]),R.ansdown);
return S;
} int qry(int l, int r) {
node ans=qry(0,0,n,l,r);
return ans.ans;
}
void print() {
for (int i=0; i<n*4; ++i) {
cout << t[i].ans << " " << t[i].ansup << " " << t[i].ansdown << "\n";
}
}
};
int n, q;
string s;
void solve() {
cin >> n >> s;
segtr tr(s,n); tr.build();
cin >> q;
while(q--) {
int l, r; cin >> l >> r; --l;
cout << tr.qry(l,r) << "\n";
//tr.print();
//cout << "\n--------------\n";
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
#ifdef disastah
cout << "Output\n\n";
#endif
/*#ifndef disastah
freopen("cardgame.in","r",stdin);
freopen("cardgame.out","w",stdout);
#endif*/
int tt=1;
// cin >> tt;
while (tt--) {
solve();
cout << "\n";
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |