One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
Input
The first line contains one integer nn (1≤n≤1051≤n≤105) — the number of bracket sequences.
Each of the following nn lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most 5⋅1055⋅105.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
Output
Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.
Examples
Input
7 )()) ) (( (( ( ) )
Output
2
Input
4 ( (( ((( (())
Output
0
Input
2 (()) ()
Output
1
Note
In the first example, it's optimal to construct two pairs: "(( )())" and "( )".
题意:
给你n个由'(' ')'组成的字符串,两两配对,最多能组成几个合法序列
For example, the sequences "( ( ) ) ( )", "( )" and "( ( ) ( ( ) ) )" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
思路:
能组成合法序列的情况:1.字符串左右括号数相等的时候 ans+=f[maxn]/2 f数组存一个字符串左括号或者右括号的数量
2. ans+=min (l :无左括号配对的右括号数量 , r :无右括号配对的左括号数量)
代码:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e5*5+5;
int f[maxn*2+1];
int n;
int main()
{
cin>>n;
while(n--)
{
int l=0,r=0;
string s;
cin>>s;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(') r++;
else if(s[i]==')')
r>0?r--:l--;
}
if(l==0) f[maxn+r]++;
else if(r==0) f[maxn+l]++;
}
int ans=f[maxn]/2; //左括号=右括号的情况
for(int i=1;i<=maxn;i++)
ans+=min(f[maxn+i],f[maxn-i]);
cout<<ans<<endl;
return 0;
}