G Parenthesis
Bobo 有一个平衡的括号序列
P
=
p
1
p
2
…
p
n
P = p_1p_2\dots p_n
P=p1p2…pn长度为 n。
有q次询问。 第 i 个问题是
p
a
i
p_{a_i}
pai和
p
b
i
p_{b_i}
pbi交换后 P 是否保持平衡。
请注意,问题是个别问题,因此不会影响其他人。
括号序列 S 是平衡的当且仅当:
1.S 为空
2.存在平衡括号序列A,B使得S = AB
3. 存在平衡括号序列S’,使得S = (S’)
#include<bits/stdc++.h>
#include <unordered_map>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
template<class...Args>
void debug(Args... args) {//Parameter pack
auto tmp = { (cout << args << ' ', 0)... };
cout << "\n";
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 1e6 + 5;
const ll MOD = 998244353;
const ll INF = 0x7fffffff;
int w[N];
struct node {
int l, r;
int minv;
} tree[N << 2];
void push_up(int root) {
tree[root].minv = min(tree[root << 1].minv, tree[root << 1 | 1].minv);
}
void build(int root, int l, int r) {
if (l == r)tree[root] = { l,r,w[l] };//叶子节点
else {
tree[root] = { l,r };//其余节点
int mid = (l + r) >> 1;
build(root << 1, l, mid);
build(root << 1 | 1, mid + 1, r);
push_up(root);
}
}
int query(int root, int l, int r) {
if (l <= tree[root].l && tree[root].r <= r)return tree[root].minv;
int mid = tree[root].l + tree[root].r >> 1;
if (r <= mid)return query(root << 1, l, r);
else if (l > mid)return query(root << 1 | 1, l, r);
else {
int left = query(root << 1, l, r);
int right = query(root << 1 | 1, l, r);
int ans = min(left, right);
return ans;
}
}
int a[N];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, m;
while (cin >> n >> m) {
memset(w, 0, sizeof w);
string s;
cin >> s;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(')w[i + 1] = w[i] +1;
if (s[i] == ')')w[i + 1] = w[i] -1;
}
build(1, 1, n);
while (m--) {
int a, b;
cin >> a >> b;
if (a > b)swap(a, b);
if (s[a - 1] == s[b - 1] || s[b - 1] == '(')cout << "Yes\n";
else {
if (query(1, a, b - 1) >= 2)cout << "Yes\n";
else cout << "No\n";
}
}
}
return 0;
}
貌似暴力也能过
#include<bits/stdc++.h>
#include <unordered_map>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
template<class...Args>
void debug(Args... args) {//Parameter pack
auto tmp = { (cout << args << ' ', 0)... };
cout << "\n";
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 1e6 + 5;
const ll MOD = 998244353;
const ll INF = 0x7fffffff;
char s[N];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, q;
cin >> n >> q;
for (int i = 0; i < n; i++)cin >> s[i];
for (int i = 0; i < q; i++) {
int x, y;
cin >> x >> y;
if (x > y)swap(x, y);
if (s[x - 1] == s[y - 1] || s[y - 1] == '(')cout << "Yes\n";
else {
swap(s[x - 1], s[y - 1]);
int sum = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '(')sum++;
if (s[i] == ')')sum--;
if (sum < 0)break;
}
if (sum == 0)cout << "Yes\n";
else cout << "No\n";
swap(s[x - 1], s[y - 1]);
}
}
return 0;
}