#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,-3});
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,0),us2(n,0);
int bl=0;
for(int i=l;i<=r;i++){
bl+=(s[i]=='C'?1:-1);
if(bl<0){
bl++;
us2[i]=1;
assert(lwr[i]<(l-1));
}
}
bl=0;
for(int i=r;i>=l;i--){
bl+=(s[i]=='C'?1:-1);
if(us2[i]) bl++,answ++;
if(bl<0){
bl++;
answ++;
}
}
cout<<answ<<endl;
//cout<<answ<<endl;
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
27 ms |
26180 KB |
Output is correct |
2 |
Correct |
25 ms |
26188 KB |
Output is correct |
3 |
Correct |
26 ms |
26144 KB |
Output is correct |
4 |
Correct |
27 ms |
26124 KB |
Output is correct |
5 |
Correct |
22 ms |
26220 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
27 ms |
26180 KB |
Output is correct |
2 |
Correct |
25 ms |
26188 KB |
Output is correct |
3 |
Correct |
26 ms |
26144 KB |
Output is correct |
4 |
Correct |
27 ms |
26124 KB |
Output is correct |
5 |
Correct |
22 ms |
26220 KB |
Output is correct |
6 |
Execution timed out |
3095 ms |
39428 KB |
Time limit exceeded |
7 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
27 ms |
26180 KB |
Output is correct |
2 |
Correct |
25 ms |
26188 KB |
Output is correct |
3 |
Correct |
26 ms |
26144 KB |
Output is correct |
4 |
Correct |
27 ms |
26124 KB |
Output is correct |
5 |
Correct |
22 ms |
26220 KB |
Output is correct |
6 |
Execution timed out |
3095 ms |
39428 KB |
Time limit exceeded |
7 |
Halted |
0 ms |
0 KB |
- |