吴承恩中学老师图片:一道Pascal题目(zju1423)

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/03 11:50:11
zju 1423 【题目大意】
删除多余括号
输入一个表达式,去掉不必要的括号和空格.
Sample Input

3 [测试数据的个数,它在10以内,下面每个测试数据的长度在255以内]
(A-B + C) - (A+(B - C)) - (C-(D- E) )
((A)-( (B)))
A-(B+C)

Sample Output

A-B+C-(A+B-C)-(C-(D-E))
A-B
A-(B+C)

You have typed the report of your term project in your personal computer. There are several one line arithmetic expressions in your report. There is no redundant parentheses in the expressions (omitting a pair of redundant matching parentheses does not change the value of the expression). In your absence, your little brother inserts some redundant matching parentheses in the expressions of your report. Assume that the expressions remain syntactically correct and evaluate to their original value (the value before inserting redundant parentheses). To restore your report to its original form, you are to write a program to omit all redundant parentheses.

To make life easier, consider the following simplifying assumptions:

1. The input file contains a number of expressions, each in one separate line.

2. Variables in the expressions are only single uppercase letters.

3. Operators in the expressions are only binary '+' and binary '-'.

Note that the only transformation allowed is omission of redundant parentheses, and no algebraic simplification is allowed.

Input

The input file consists of several test cases. The first line of the file contains a single number M, which is the number of test cases (1 <= M <= 10). Each of the following M lines, is exactly one correct expression. There may be arbitrarily space characters in each line. The length of each line (including spaces) is at most 255 characters.

Output

The output for each test case is the same expression without redundant parentheses. Notice that the order of operands in an input expression and its corresponding output should be the same. Each output expression must be on a separate line. Space characters should be omitted in the output expressions.

Sample Input

3
(A-B + C) - (A+(B - C)) - (C-(D- E) )
((A)-( (B)))
A-(B+C)

Sample Output

A-B+C-(A+B-C)-(C-(D-E))
A-B
A-(B+C)

function f(st:string;i:integer):char;
begin
while st[i]=' ' do
dec(i);
f:=st[i];
end;
function fun(st:string):string;
var i,j,t,l,g,b,m,n,k:integer;
a:array[1..255] of boolean;
begin
l:=length(st);
fillchar(a,sizeof(a),false);
for i:=1 to l-2 do
if st[i]='(' then
begin
t:=1;j:=i;g:=0;
while (t<>0) do
begin
inc(j);
if st[j]='(' then inc(t)
else if st[j]=')' then dec(t)
else if st[j]='-' then inc(g)
else if st[j]='+' then inc(g);
end;
if (i=1)or(f(st,i-1)<>'-')or(g=0) then
begin
a[i]:=true;
a[j]:=true;
end;
end;
for i:=l downto 1 do
if a[i] then
delete(st,i,1);
for i:=l downto 1 do
if st[i]=' ' then delete(st,i,1);
fun:=st;
end;
var st:string;
i:integer;
begin
readln(i);
for i:=1 to i do
begin
readln(st);
writeln(fun(St));
end;
end.