7454 - Parentheses
A bracket is a punctuation mark, which is used in matched pairs, usually used within articles or
programs. Brackets include round brackets, square brackets, curly brackets, angle brackets, and various
other pairs of symbols. Let’s focus on the round brackets, also called parentheses.
A sequence of parentheses is said to be well-formed if the parentheses are properly nested. For example,
A = a1a2 … a18 = “(()())()()()(())()” is well-formed, but B = b1b2 … b18 = “(()())))(((((())((”
is not. (See Figure 1.) More formally, a sequence of parentheses P = p1p2 … pn is well-formed if
(1) when scanning it from p1 to pn, the number of right parentheses does not exceed the number of
left parentheses at any state, and
(2) the numbers of left and right parentheses are equal.
Figure 1. Two sequences of parentheses.
AutoText is a company, which is developing a text editor for programmers. The new editor will
provide many powerful functions to automatically correct typing errors. On a keyboard, the left and
right parentheses are adjacent. Thus, it is often that “)” is mistyped as “(” or vice versa. And therefore,
one of the functions AutoText wants to provide is to automatically convert a sequence of parentheses
P (that may not be well-formed) into a wellformed sequence P
′
. In the conversion, the only allowed
operation is to reverse a parenthesis (i.e., either to replace a “(” with a “)” or to replace a “)” with
a “(”). For example, in Figure 1, we can convert B into the well-formed sequence A by performing 4
reverse operations on b7, b10, b12, b18 . Of course, there may be several ways to convert a sequence into
a well-formed sequence. A conversion is optimal if it uses the minimum number of reverse operations.
Please write a program to compute the minimum number of reverse operations that make a given
sequence of parentheses P = p1p2 … pn well-formed.
Input
The first line contains an integer T ≤ 10 indicating the number of test cases. The first line of each test
case contains an even integer n, 2 ≤ n ≤ 100, indicating the length of P. Next, the second line gives
the sequence P.
Output
For each test case, output the minimum number of reverse operations that make P well-formed.
Sample Input
3
18
(()())))(((((())((
2
()
8
(()))()(
Sample Output
4
0
2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char q[110]; //分配栈的大小
int main()
{
int T,top,n,i,s;
char a[110];
scanf("%d",&T);
while(T--)
{
memset(a,0,sizeof(a));
s=0;
top=0;
scanf("%d",&n);
getchar(); //吃回车(用scanf("%s",a);输入省略此句)
gets(a);
for(i=0;i<n;i++)
{
if(a[i]=='(')
q[top++]=a[i]; //‘(’直接入栈
else if(a[i]==')'&&q[top-1]=='(')
top--; //匹配成功出栈
else if(a[i]==')'&&q[top-1]!='(')
{
q[top++]='(';
s++; //')'无匹配的左括号,将其变为‘(’入栈,并记录变化次数
}
else
{
q[top++]='(';
s++; //同上
}
}
printf("%d\n",(top/2)+s); //最后栈中只剩‘(’,其一半变为‘)’即匹配,再加上之前变换的次数
}
return 0;
}