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 ll long long
#define MAXN 500010
using namespace std;
ll n,a[MAXN],sz;
struct element
{
ll pref=0,suff=0,sum=0,minn;
};
element Merge(element x,element y)
{
element z;
z.pref=min(x.pref,x.sum+y.pref);
z.suff=min(y.suff,x.suff+y.sum);
z.sum=x.sum+y.sum;
z.minn=min({0ll,x.pref+y.suff,x.minn+y.sum,x.sum+y.minn});
return z;
}
element neutral_element;
struct seg_tree
{
vector<element> st;
void Init()
{
sz=1;
while (sz<n)
sz <<= 1;
st.resize(2*sz+2);
}
void Build()
{
for (ll i=sz;i<sz+n;i++)
st[i]={min(0ll,a[i-sz+1]),min(0ll,a[i-sz+1]),a[i-sz+1],min(0ll,a[i-sz+1])};
for (ll i=sz-1;i>0;i--)
st[i]=Merge(st[2*i],st[2*i+1]);
}
element Calc(ll l,ll r,ll x,ll lx,ll rx)
{
if (lx>r || rx<l)
return neutral_element;
if (lx>=l && rx<=r)
return st[x];
ll mid=(lx+rx)/2;
return Merge(Calc(l,r,2*x,lx,mid),Calc(l,r,2*x+1,mid+1,rx));
}
};
seg_tree S;
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll q,l,r;
string s;
cin >> n >> s;
for (ll i=0;i<n;i++)
a[i+1]=(s[i]=='T')?-1 : 1;
S.Init();
S.Build();
cin >> q;
while (q--)
{
cin >> l >> r;
element ans=S.Calc(l,r,1,1,sz);
cout << abs(ans.minn) << "\n";
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |