-
Notifications
You must be signed in to change notification settings - Fork 0
/
LOAIBONGOACTHUA.cpp
112 lines (108 loc) · 2.35 KB
/
LOAIBONGOACTHUA.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
#include <stack>
using namespace std;
string deleteSpace (string x) //a+ b -> a+b
{
string rs = "";
for (int i=0; i<x.length(); i++)
if (x[i]!=' ')
rs+=x[i];
return rs;
}
string delete_1 (string x) //delete string like (a)->a || ((a+b))->(a+b)
{
stack <char> s;
stack <int> index;
int dele[300] = {0};
for (int i=0; i<x.length(); i++)
{
if (x[i]==')')
{
int flag = 0;
while (s.top()!='(')
{
char top = s.top();
if (top=='+' || top=='-')
flag = 1;
s.pop();
index.pop();
}
if (flag == 0)
{
dele[index.top()] = 1;
dele[i] = 1;
}
s.pop();
index.pop();
}
else
{
s.push(x[i]);
index.push(i);
}
}
string rs = "";
for (int i=0; i<x.length(); i++)
{
if (dele[i]==0)
rs+=x[i];
}
return rs;
}
string delete_2 (string x) //delete string like ((a+b)+c)->(a+b+c) || (a+(b-c))->(a+b-c)
{
stack <char> s;
stack <int> index;
int dele[300] = {0};
for (int i=x.length()-1; i>=0; i--)
{
if (x[i]=='(')
{
int flag = 1;
if (i==0 || x[i-1]!='-')
flag = 0;
while (s.top()!=')')
{
s.pop();
index.pop();
}
if (flag == 0)
{
dele[index.top()] = 1;
dele[i] = 1;
}
s.pop();
index.pop();
}
else
{
s.push(x[i]);
index.push(i);
}
}
string rs="";
for (int i=0; i<x.length(); i++)
{
if (dele[i]==0)
rs+=x[i];
}
return rs;
}
int main ()
{
string str = "";
int n;
cin>>n;
cin.ignore();
while (1)
{
if (n==0) break;
n--;
getline(cin, str);
string str_no_space = deleteSpace(str);
string str_1 = delete_1(str_no_space);
string str_2 = delete_2(str_1);
cout<<str_2<<endl;
}
return 0;
}