E. Almost Regular Bracket Sequence
time limit per test 3 seconds
memory limit per test 256 megabytes
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≤10^6) — 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
input
6
(((())
output
3
input
6
()()()
output
0
input
1
)
output
0
input
8
)))(((((
output
0
当且仅当栈内有且仅有两个相同字符时进行计算,对左右括号分情况讨论向不同方向计数
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
stack< pair<char,int> > input;
char save[n];
char temp;
int Count=0;
for(int i=0;i<n;i++){
cin>>temp;
save[i]=temp;
if(temp==')' && input.size()!=0 && input.top().first=='(') input.pop();
else input.push(make_pair(temp,i));
}
if(input.size()==0){
cout<<0;
return 0;
}
pair<char,int> after =input.top();
input.pop();
int work=0;
if(input.size()!=1 || after.first!=input.top().first){
cout<<0;
return 0;
}
else if(after.first=='('){
for(int i=after.second;i<n;i++)
if(save[i]=='(') work++;
}
else{
for(int i=input.top().second;i>=0;i--)
if(save[i]==')') work++;
}
cout<<work;
return 0;
}