cf1214C C. Bad Sequence

C. Bad Sequence
time limit per test1 second
memory limit per test512 megabytes
inputstandard input
outputstandard output
Petya’s friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.

To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning “(” into “)” or vice versa) isn’t allowed.

We remind that bracket sequence s is called correct if:

s is empty;
s is equal to “(t)”, where t is correct bracket sequence;
s is equal to t1t2, i.e. concatenation of t1 and t2, where t1 and t2 are correct bracket sequences.
For example, “(()())”, “()” are correct, while “)(” and “())” are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

Input
First of line of input contains a single number n (1≤n≤200000) — length of the sequence which Petya received for his birthday.

Second line of the input contains bracket sequence of length n, containing symbols “(” and “)”.

Output
Print “Yes” if Petya can make his sequence correct moving at most one bracket. Otherwise print “No”.

Examples
input

2
)(
output
Yes
input
3
(()
output
No
input
2
()
output
Yes
input
10
)))))(((((
output
No
Note
In the first example, Petya can move first bracket to the end, thus turning the sequence into “()”, which is correct bracket sequence.

In the second example, there is no way to move at most one bracket so that the sequence becomes correct.

In the third example, the sequence is already correct and there’s no need to move brackets.
題意: 給出字符串長度,和一段只含左右括號的字符,並定義該字符序列是好的條件爲括號匹配或者只通過移一個括號,能使其完全匹配,如果滿足上述條件,則輸出Yes,否則輸出No。
思路: 首先對n進行奇偶判斷,奇數直接輸出No,因爲左括號數不等於右括號數,如果爲偶數則用棧去模擬括號是否匹配(遇到左括號入棧,遇到右括號且棧不爲空出棧),同時記錄左括號數目和右括號數目,如果左括號數目不等於右括號數目,直接輸出No,如果相等,再判斷棧裏的剩餘左括號數目,如果其數目小於等於1,則輸出Yes,否則輸出No。詳情看代碼和註釋。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
char s[N];
int main() {
	int n;
	scanf("%d", &n);
	scanf("%s", s);
	if (n % 2 == 1) printf("No\n");
	else {
		stack<char> st;
		int num = 0, num1 = 0;
		for (int i = 0; i < n; i++) {
			if (s[i] == '(') st.push(s[i]); // 遇到左括號,直接入棧 
			else if (s[i] == ')' && !st.empty()) st.pop(); // 遇到右括號且當前棧不爲空,出棧 
			if (s[i] == '(') num++; // 記錄左括號數目 
			else num1++; // 記錄右括號數目
		}
		if (st.empty() && num == num1) printf("Yes\n"); // 棧爲空且左右括號數目相等說明括號匹配 
		else {
			if (st.size() > 1 || num != num1) printf("No\n"); // 如果棧中剩餘左括號數目大於1或左右括號數目不相等,輸出No 
			else printf("Yes\n"); // 否則輸出Yes 
		}
	}
	return 0; 
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章