csu 1809 Parenthesis

时间:2023-03-09 16:09:55
csu 1809 Parenthesis

题目见此

分析,把‘(’当成1, ‘)’当成-1, 计算前缀和sum。

记交换括号左边的序号为u, 右边为v,讨论左右括号:

1、s[u] == ‘(’ && s[v] == ‘)’ 那么[u, v - 1]的前缀和会全部-2

2、s[u] == ‘(’ && s[v] == ‘(’ 显然

3、s[u] == ‘)’ && s[v] == ‘(’ 那么[u, v - 1]的前缀和会全部+2

4、s[u] == ‘)’ && s[v] == ‘)’ 显然

对于一个括号序列,序列合法的要求是对∃sum[i]>=0 && sum[N]=0, 所以2,3,4的变换都不会改变序列的合法性。对于第一种情况,只要min(sum[i])>=2,i∈[u,v−1]即可。可以用ST或者线段树实现快速查询最小值。

/*****************************************************/
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <map>
#include <set>
#include <ctime>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define offcin ios::sync_with_stdio(false)
#define sigma_size 26
#define lson l,m,v<<1
#define rson m+1,r,v<<1|1
#define slch v<<1
#define srch v<<1|1
#define sgetmid int m = (l+r)>>1
#define LL long long
#define ull unsigned long long
#define mem(x,v) memset(x,v,sizeof(x))
#define lowbit(x) (x&-x)
#define bits(a) __builtin_popcount(a)
#define mk make_pair
#define pb push_back
#define fi first
#define se second const int INF = 0x3f3f3f3f;
const LL INFF = 1e18;
const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-9;
const LL mod = 1e9+7;
const int maxmat = 10;
const ull BASE = 31; /*****************************************************/ const int maxn = 2e5 + 5;
int N, Q;
char s[maxn];
int a[maxn];
int seg[maxn << 2], col[maxn << 2];
void PushUp(int v) {
seg[v] = min(seg[slch], seg[srch]);
}
void build(int l, int r, int v) {
if (l == r) seg[v] = a[l];
else {
sgetmid;
build(lson);
build(rson);
PushUp(v);
}
}
int query(int L, int R, int l, int r, int v) {
if (L <= l && r <= R) return seg[v];
sgetmid;
int ans = INF;
if (L <= m) ans = min(ans, query(L, R, lson));
if (R > m) ans = min(ans, query(L, R, rson));
return ans;
}
int main(int argc, char const *argv[]) {
int N, Q;
while (~scanf("%d%d", &N, &Q)) {
mem(seg, 0); mem(a, 0);
scanf("%s", s);
for (int i = 1; i <= N; i ++) {
if (s[i - 1] == '(') a[i] = a[i - 1] + 1;
else a[i] = a[i - 1] - 1;
}
build(1, N, 1);
for (int i = 0; i < Q; i ++) {
int u, v;
scanf("%d%d", &u, &v);
if (u > v) swap(u, v);
if (s[u - 1] == '(' && s[v - 1] == ')') {
int pos = query(u, v - 1, 1, N, 1);
if (pos >= 2) puts("Yes");
else puts("No");
}
else puts("Yes");
}
}
return 0;
}