#include <bits/stdc++.h>
#define vec vector
#define f first
#define s second
#define endl '\n'
#define pb push_back
#define sz(x) (int)x.size()
using namespace std;
typedef pair<int,int> pii;
const int N=5e5+1;
int lft[N],rgt[N],lwr[N];
vec<pii>toadd[N];
int ans[N];
vec<pii>qry[N];
int mn[N][20],mx[N][20];
int lvl[N];
int getmn(int l,int r){
int x=lvl[r-l+1];
return min(mn[l][x],mn[r-(1<<x)+1][x]);
}
int getmx(int l,int r){
int x=lvl[r-l+1];
return max(mx[l][x],mx[r-(1<<x)+1][x]);
}
signed main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n,q;
cin>>n;
vec<int>a(n);string s;
vec<int>x(n);
cin>>s;s.insert(s.begin(),'w');
for(int i=1;i<=n;i++){
a[i]=(i?a[i-1]:0)+(s[i]=='C'?1:-1);
// mn[i][0]=mx[i][0]=a[i];
}
for(int i=1;i<=n;i++){
x[i]=(i?a[i-1]:0);
mn[i][0]=mx[i][0]=x[i];
}
for(int i=2;i<N;i++) lvl[i]=lvl[i/2]+1;
for(int j=1;j<20;j++){
for(int i=0;i+(1<<(j-1))<n;i++){
mn[i][j]=min(mn[i][j-1],mn[i+(1<<(j-1))][j-1]);
mx[i][j]=max(mx[i][j-1],mx[i+(1<<(j-1))][j-1]);
}
}
vec<pii>vc;
vc.pb({-2e9,-1});
for(int i=0;i<=n;i++){
while(sz(vc) && vc.back().f>a[i]) vc.pop_back();
lft[i]=vc.back().s+1;
vc.pb({a[i],i});
}
vc.clear();
vc.pb({2e9,n+1});
for(int i=n;i>=0;i--){
while(sz(vc) && vc.back().f<a[i]) vc.pop_back();
rgt[i]=vc.back().s-1;
vc.pb({a[i],i});
}
vc.clear();
{
vc.pb({-2e9,-1});
for(int i=0;i<=n;i++){
while(sz(vc) && vc.back().f>a[i]) vc.pop_back();
lwr[i]=vc.back().s;
vc.pb({a[i],i});
}
}
cin>>q;
while(q--){
int l,r;
cin>>l>>r;
int answ=0;
// map<int,int>mp1,mp2;
vec<int>us1(n+1,0),us2(n+1,0);
int bl=0;
for(int i=l;i<=r;i++){
bl+=(s[i]=='C'?1:-1);
if(bl<0){
bl++;
us2[i]=1;
answ++;
assert(lwr[i]<(l-1));
}
}
//cout<<"FIRST"<<answ<<endl;
bl=0;
int st1=0,st2=0;
int j=r-1;
for(int i=r;i>=l;i--){
if(a[j]<a[i-1]) {j=i-1;}
bl+=(s[i]=='C'?1:-1);
if(us2[i]) bl++;
if(bl<0){
bl++;
answ++;st2++;
// cout<<"YO "<<i<<endl;
}
}
st1=a[j];
for(int i=j+1;i<=r;i++){
if(lwr[i]<l-1) st1--;
}
st1-=a[r];
st1=max(st1,0);
//cout<<st1<<' '<<st2<<endl;
assert(st1==st2);
cout<<answ<<endl;
//cout<<answ<<endl;
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
49 ms |
52868 KB |
Execution killed with signal 6 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
49 ms |
52868 KB |
Execution killed with signal 6 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
49 ms |
52868 KB |
Execution killed with signal 6 |
2 |
Halted |
0 ms |
0 KB |
- |