# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
1050068 | matere | Election (BOI18_election) | C++14 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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;
}
}