G Parenthesis

Bobo has a balanced parenthesis sequence P=p1p2…pnP = p_1p_2\dots p_nP=p1​p2​…pn​ of length n
and q questions.
The i-th question is whether P remains balanced after paip_{a_i}pai​​ and pbip_{b_i}pbi​​ 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’).
    输入描述:

The input contains at most 30 sets. For each set:
The first line contains two integers n, q (2≤n≤105,1≤q≤1052 \leq n \leq 10^5, 1 \leq q \leq 10^52≤n≤105,1≤q≤105).
The second line contains n characters p1p2…pnp_1p_2\dots p_np1​p2​…pn​.
The i-th of the last q lines contains 2 integers ai,bia_i, b_iai​,bi​ (1≤ai,bi≤n,ai≠bi1 \leq a_i, b_i \leq n, a_i \neq b_i1≤ai​,bi​≤n,ai​​=bi​).

输出描述:

For each question, output “Yes” if P remains balanced, or “No” otherwise.

示例1
输入
复制

4 2
(())
1 3
2 3

输出
复制

No
Yes

示例2
输入
复制

2 1
()
1 2

输出
复制

扫描二维码关注公众号,回复: 8562128 查看本文章

No

把左括号赋值为1, 右括号赋值为-1, 交换后求前缀和,若区间内的值都大于等于0就yes,否则为no。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;

const int maxn = 1e5 + 10;
int n, m;
char str[maxn];
int sum[maxn];

void init()
{
	for(int i = 1; i <= n; i++)
	{
		if(str[i] == '(')
			sum[i] += sum[i - 1] + 1;
		else if(str[i] == ')')
			sum[i] += sum[i - 1] - 1;
	}
}

int main()
{
	while(scanf("%d%d", &n, &m) != EOF)
	{
		memset(str, 0, sizeof(str));
		memset(sum, 0, sizeof(sum));
		scanf("%s", str + 1);
		init();
		int l, r;
//		for(int i = 1; i <= n; i++)
//			cout << sum[i] << " ";
		for(int i = 0; i < m; i++)
		{
			scanf("%d%d", &l, &r);
			if(l > r)
				swap(l, r);
			int f = 0;
			if(str[l] == '(' && str[r] == ')')
			for(int j = l; j < r; j++)
			{
				if(sum[j] - 2 < 0)
				{
					f = 1;
					break;
				}
			}
			if(f)
				printf("No\n");
			else 
			printf("Yes\n");
		}
	}
	return 0;
}
发布了73 篇原创文章 · 获赞 15 · 访问量 8109

猜你喜欢

转载自blog.csdn.net/ln2037/article/details/102314834
今日推荐