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;
const int maxn = 500005;
int n;
string s;
struct segment_tree
{
struct state
{
int sum;
int max_pref;
int max_suff;
int ans;
state()
{
sum = 0;
max_pref = 0;
max_suff = 0;
ans = 0;
}
state(int _sum, int _max_pref, int _max_suff, int _ans)
{
sum = _sum;
max_pref = _max_pref;
max_suff = _max_suff;
ans = _ans;
}
};
state tree[4 * maxn];
state combine(state left_child, state right_child)
{
state result;
result.sum = left_child.sum + right_child.sum;
result.max_pref = max(left_child.max_pref, left_child.sum + right_child.max_pref);
result.max_suff = max(right_child.max_suff, right_child.sum + left_child.max_suff);
result.ans = max(max(left_child.ans + right_child.sum, left_child.sum + right_child.ans), left_child.max_pref + right_child.max_suff);
return result;
}
void build(int node, int l, int r)
{
if (l == r)
{
if (s[l] == 'T')
{
tree[node] = state(1, 1, 1, 1);
}
else
{
tree[node] = state(-1, 0, 0, 0);
}
return;
}
int mid = (l + r) / 2;
build(2 * node, l, mid);
build(2 * node + 1, mid + 1, r);
tree[node] = combine(tree[2 * node], tree[2 * node + 1]);
}
state query(int node, int l, int r, int ql, int qr)
{
if (l > qr || r < ql)
{
return state(0, 0, 0, 0);
}
if (ql <= l && r <= qr)
{
return tree[node];
}
int mid = (l + r) / 2;
return combine(query(2 * node, l, mid, ql, qr), query(2 * node + 1, mid + 1, r, ql, qr));
}
int query(int l, int r)
{
return query(1, 1, n, l, r).ans;
}
};
segment_tree tree;
void fastIO()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int main()
{
fastIO();
cin >> n >> s;
s = '#' + s;
tree.build(1, 1, n);
int q;
cin >> q;
while (q--)
{
int l, r;
cin >> l >> r;
cout << tree.query(l, r) << "\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... |