TOJ 2196 ZOJ 1423 (Your)((Term)((Project)))
(Your)((Term)((Project)))时间限制(普通/Java):1000MS/10000MS 运行内存限制:65536KByte
描述
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.
输入
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.
输出
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.
样例输入
3
(A-B + C) - (A+(B - C)) - (C-(D- E) )
((A)-( (B)))
A-(B+C)
样例输出
A-B+C-(A+B-C)-(C-(D-E))
A-B
A-(B+C)
字符串处理 去掉可以去掉的括号
减号后面的一对括号并且括号里不只有1个字母 这种条件是不可以去掉的 其他可以去掉
#include <stdio.h> #include <iostream> #include <string.h> #include <string> using namespace std; int main() { char a[300],b[300]; int map[300]; int t,i,j,n; scanf("%d",&t); getchar(); while(t--) { gets(a); memset(map,0,sizeof(map)); for(i = 0,j = 0; a[i]; i++)//去空格 { if(a[i] != ' ') { b[j++] = a[i]; } } b[j] = 0; n = j; for(i = 0; i < n; i++) { if(b[i] == '-' && b[i+1] == '(') { map[i+1] = 1; int count = 0,flag = 0; for(j = i + 1;; j++) { if(b[j] == '(') { count++; flag = 1; } else if(b[j] == ')') { count--; if(!count && flag) { map[j] = 1; break; } } } } } for(i = 0;i < n; i++) { if(map[i] && b[i] == '(') { int count = 0, count2 = 0; for(j = i;; j++) { if(b[j] == '(') { count++; } else if(b[j] == ')') { count--; if(!count) { if(count2 == 1) { map[j] = 0; map[i] = 0; } break; } } else { count2++; } } } } //puts(b); for(i = 0;i < n; i++) { if(b[i] == '(' || b[i] == ')') { if(map[i]) { printf("%c",b[i]); } } else printf("%c",b[i]); } puts(""); } return 0; }
补充:软件开发 , C++ ,