You are given a bracket sequence s consisting of n opening ‘(’ and closing ‘)’ brackets.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters ‘1’ and ‘+’ between the original characters of the sequence. For example, bracket sequences “()()”, “(())” are regular (the resulting expressions are: “(1)+(1)”, “((1+1)+1)”), and “)(” and “(” are not.
You can change the type of some bracket si. It means that if si= ‘)’ then you can change it to ‘(’ and vice versa.
Your task is to calculate the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.
Input
The first line of the input contains one integer n (1≤n≤106) — the length of the bracket sequence.
The second line of the input contains the string s consisting of n opening ‘(’ and closing ‘)’ brackets.
Output
Print one integer — the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.
Examples
inputCopy
6
(((())
outputCopy
3
inputCopy
6
()()()
outputCopy
0
inputCopy
1
)
outputCopy
0
inputCopy
8
)))(((((
outputCopy
0
题意:
给你一串字符串,( 和 )在左右就是匹配,)(就不是匹配,让你改变任意一个地方的括号,(改成),)改成(,使得这个字符串是匹配的字符串,问你有多少种方法。
题解:
想法挺简单的,只要想出所有情况即可了,最后你就会发现这样一件事情:完美匹配和剩下的字符不是两个或者不是相同的就不可以,然后只需要判断剩下两个字符的情况,最后发现如果是’(’,那么从第二个多余的’(’开始接下来都是可以改变的,相反的话是第一个多余的’)‘开始都是可以改变的,举个例子:
((()))))是前面4个’)'可以改变,((()))((,只有最后一个可以被改变,因为前面的是完美匹配了,))(())只有第一个可以改变,其他是完美匹配了。
#include<bits/stdc++.h>
using namespace std;
#define pa pair<char,int>
const int N=1e6+5;
char s[N];
pa st[N];
int judge(char a,char b)
{
if(a=='('&&b==')')
return 1;
return 0;
}
int main()
{
int n,top=0;
scanf("%d",&n);
scanf("%s",s+1);
for(int i=1;i<=n;i++)
{
if(top==0||judge(st[top].first,s[i])==0)
st[++top]={s[i],i};
else
top--;
}
int k=0;
if(top==2&&st[1].first==st[2].first)
return 0*printf("%d\n",st[1].first=='('?(n-st[2].second)/2+1:(st[1].second-1)/2+1);
printf("0\n");
return 0;
}