-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonp.cpp
79 lines (68 loc) · 1.62 KB
/
onp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <string>
#include <stack>
#include <stdexcept>
#include <exception>
// Problem Description
// http://www.codechef.com/problems/ONP
using namespace std;
int scan(const string& line, int start){
int count = 1;
for(int i = start+1; i < line.size(); i++){
if (line[i] == '('){
count += 1;
}
else if(line[i] == ')'){
count -= 1;
}
if (count == 0){
return i;
}
}
throw std::invalid_argument("Not matched parentheses");
}
string scan_paren(const string& line, int start, int end){
stack<string> text;
int first_start = start+1;
int first_end;
char first = line[first_start];
string first_val;
string second_val;
if (first == '('){
first_end = scan(line, first_start+1);
first_val = scan_paren(line, first_start, first_end);
}
else{
first_end = first_start;
first_val = string {line[first_start]};
}
//cout << first_end << endl;
string oper = string {line[first_end+1]};
int second_start = first_end + 2;
char second = line[second_start];
//cout << second << endl;
int second_end;
if (second == '('){
second_end = scan(line, second_start+1);
second_val = scan_paren(line, second_start, second_end);
}
else{
second_end = second_start;
second_val = string {line[second_start]};
}
//cout << second_val << endl;
return first_val + second_val + oper;
}
int main(){
int t;
scanf("%d\n", &t);
/*
string line {"(a+(b*c))"};
cout << postfix(line,0,8) << endl;
*/
for(int i=0; i < t; i++){
string line;
getline(cin, line);
cout << scan_paren(line,-1,line.size()) << endl;
}
}