Description
Bobo has a balanced parenthesis sequence P=p
1 p
2…p
n of length n and q questions.
The i-th question is whether P remains balanced after p
ai and p
bi swapped. Note that questions are individual so that they have no affect on others.
Parenthesis sequence S is balanced if and only if:
1.
S is empty;
2.
or there exists
balanced parenthesis sequence A,B such that S=AB;
3.
or there exists
balanced parenthesis sequence S' such that S=(S').
Input
The input contains at most 30 sets. For each set:
The first line contains two integers n,q (2≤n≤10
5,1≤q≤10
5).
The second line contains n characters p
1 p
2…p
n.
The i-th of the last q lines contains 2 integers a
i,b
i (1≤a
i,b
i≤n,a
i≠b
i).
Output
For each question, output "
Yes" if P remains balanced, or "
No" otherwise.
Sample Input
4 2
(())
1 3
2 3
2 1
()
1 2
Sample Output
No YesNo
对于括号序列匹配,是有一些实用的结论的,如果一个序列是合法的,那么
以左括号为+1,右括号为-1,前缀和任何时候都不会是负数。
所以对于原序列来说,显然满足上述条件。
对于每个询问,如果两个符号相同显然是Yes
同样,如果左边的符合是-1,那么也一定是Yes,因为移动之后使得中间这段前缀和变大。
剩下就是统计区间最小值的问题了,用个rmq就ok了。
当然,由于交换的影响只是会让[L,R-1]这段区间的前缀和-2,
所以其实只要统计区间里前缀和小于2的个数即可。
#include<set> #include<map> #include<ctime> #include<cmath> #include<stack> #include<queue> #include<bitset> #include<cstdio> #include<string> #include<cstring> #include<iostream> #include<algorithm> #include<functional> #define rep(i,j,k) for (int i = j; i <= k; i++) #define per(i,j,k) for (int i = j; i >= k; i--) #define loop(i,j,k) for (int i = j;i != -1; i = k[i]) #define lson x << 1, l, mid #define rson x << 1 | 1, mid + 1, r #define ff first #define ss second #define mp(i,j) make_pair(i,j) #define pb push_back #define pii pair<int,LL> #define in(x) scanf("%d", &x); using namespace std; typedef long long LL; const int low(int x) { return x&-x; } const double eps = 1e-9; const int INF = 0x7FFFFFFF; const int mod = 1e9 + 7; const int N = 1e5 + 10; int T, n, m, l, r; char s[N]; int f[N][20], lg[N]; int rmq(int l, int r) { int k = lg[r - l + 1]; return min(f[l][k], f[r - (1 << k) + 1][k]); } int main() { while (scanf("%d%d", &n, &m) != EOF) { scanf("%s", s + 1); int x = 0; lg[0] = -1; rep(i, 1, n) { x += s[i] == '(' ? 1 : -1; f[i][0] = x; lg[i] = lg[i / 2] + 1; } for (int j = 1; (1 << j) <= n; j++) { rep(i, 1, n) { if (i + (1 << j - 1) > n) break; f[i][j] = min(f[i][j - 1], f[i + (1 << j - 1)][j - 1]); } } while (m--) { scanf("%d%d", &l, &r); if (l > r) swap(l, r); if (s[l] == s[r] || s[l] == ')') { printf("Yes\n"); continue; } if (rmq(l, r - 1) - 2 < 0) printf("No\n"); else printf("Yes\n"); } } return 0; }