# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1050068 | matere | Election (BOI18_election) | C++14 | 0 ms | 0 KiB |
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>
using namespace std;
int a[500005],pref[500005],suf[500005],lg[500005];
pair<int,int>spp[500005][20],sps[500005][20];
vector<int>v;
int main(){
int n;
char c;
cin>>n;
for(int i=2;i<=500004;i++) lg[i]=lg[i/2]+1;
for(int i=1;i<=500004;i++) spp[i][0].first=sps[i][0].first=1e9;
v.push_back(0);
for(int i=1;i<=n;i++){
cin>>c;
if(c=='T') v.push_back(i);
a[i]=(c=='C')*2-1;
pref[i]=pref[i-1]+a[i];
spp[i][0].first=pref[i];
spp[i][0].second=i;
}
v.push_back(n+1);
for(int i=n;i>=1;i--){
suf[i]=suf[i+1]+a[i];
sps[i][0].first=suf[i];
sps[i][0].second=i;
}
for(int pr=1;pr<=19;pr++){
for(int i=1;i<=n;i++){
spp[i][pr].second=spp[i][pr-1].second;
sps[i][pr].second=sps[i][pr-1].second;
if(spp[i][pr-1].first>spp[min(n,i+(1<<(pr-1)))][pr-1].first) spp[i][pr].second=spp[min(n,i+(1<<(pr-1)))][pr-1].second;
if(sps[i][pr-1].first>sps[min(n,i+(1<<(pr-1)))][pr-1].first) sps[i][pr].second=sps[min(n,i+(1<<(pr-1)))][pr-1].second;
spp[i][pr].first=min(spp[i][pr-1].first,spp[min(n,i+(1<<(pr-1)))][pr-1].first);
sps[i][pr].first=min(sps[i][pr-1].first,sps[min(n,i+(1<<(pr-1)))][pr-1].first);
}
}
int q;
cin>>q;
for(int i=1;i<=q;i++){
int l,r;
cin>>l>>r;
int mn1=min(spp[l][lg[r-l+1]].first,spp[r-(1<<lg[r-l+1])+1][lg[r-l+1]].first);
int mn1i=spp[l][lg[r-l+1]].second;
if(spp[l][lg[r-l+1]].first>spp[r-(1<<lg[r-l+1])+1][lg[r-l+1]].first) mn1i=spp[r-(1<<lg[r-l+1])+1][lg[r-l+1]].second;
int mn2=min(sps[l][lg[r-l+1]].first,sps[r-(1<<lg[r-l+1])+1][lg[r-l+1]].first);
int mn2i=sps[l][lg[r-l+1]].second;
if(sps[l][lg[r-l+1]].first>sps[r-(1<<lg[r-l+1])+1][lg[r-l+1]].first) mn2i=sps[r-(1<<lg[r-l+1])+1][lg[r-l+1]].second;
mn1-=pref[l-1];
mn2-=suf[r+1];
cout<<max((long long)-mn1,max((long long)-mn2,-mn1-mn2-((upper_bound(v.begin(),v.end(),mn1i)-v.begin())-(lower_bound(v.begin(),v.end(),mn2i)-v.begin()))))<<endl;
}
}