SP61 BRCKTS - Brackets
单点修改,区间询问,不难想到线段树。
所以我们把这个问题转化成另外一个问题,设 ( 符号表示
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
const int N = 3e4 + 5;
int t, n, p[N], m;
string s;
class SegmentTree
{
public:
struct Node
{
int l, r, minn, add;
};
Node tr[N << 2];
void push_up(int u)
{
tr[u].minn = min(tr[u << 1].minn, tr[u << 1 | 1].minn);
}
void push_down(int u)
{
Node& root = tr[u], & left = tr[u << 1], & right = tr[u << 1 | 1];
if (root.add)
{
left.add += root.add;
left.minn += root.add;
right.add += root.add;
right.minn += root.add;
root.add = 0;
}
}
void build(int u, int l, int r)
{
tr[u] = { l, r, (int)1e9, 0 };
if (l == r)
{
tr[u].minn = p[l];
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
push_up(u);
}
void update(int u, int l, int r, int ad)
{
if (tr[u].l >= l and tr[u].r <= r)
{
tr[u].add += ad;
tr[u].minn += ad;
return;
}
push_down(u);
int mid(tr[u].l + tr[u].r >> 1);
if (l <= mid) update(u << 1, l, r, ad);
if (r > mid) update(u << 1 | 1, l, r, ad);
push_up(u);
}
int query(int u, int l, int r)
{
if (tr[u].l >= l and tr[u].r <= r)
{
return tr[u].minn;
}
push_down(u);
int res = 1e9, mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) res = query(u << 1, l, r);
if (r > mid) res = min(res, query(u << 1 | 1, l, r));
return res;
}
};
SegmentTree sg;
int main()
{
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
t = 10;
while (t--)
{
memset(p, 0, sizeof p);
cout << "Test " << 10 - t << ":\n";
cin >> n >> s;
for (int i = 1; i <= n; i++)
{
p[i] = p[i - 1] + (s[i - 1] == '(' ? 1 : -1);
}
sg.build(1, 1, n);
cin >> m;
while (m--)
{
int x;
cin >> x;
if (x)
{
if (s[x - 1] == '(')
{
sg.update(1, x, n, -2);
s[x - 1] = ')';
}
else
{
sg.update(1, x, n, 2);
s[x - 1] = '(';
}
}
else
{
if (sg.query(1, 1, n) == 0 and sg.query(1, n, n) == 0) cout << "YES\n";
else cout << "NO\n";
}
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现