-
Notifications
You must be signed in to change notification settings - Fork 2
/
公共表达式消除.cpp
87 lines (78 loc) · 1.35 KB
/
公共表达式消除.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
#include<cstdio>
#include<cstring>
#include<stack>
#include<string>
#include<map>
#include<cctype>
using namespace std;
const int maxn = 50000;
char buf[maxn], *p;
int done[maxn];
struct node{
string str;
int left, right, hash;
bool operator < (const node &n) const{
if(hash != n.hash) return hash < n.hash;
if(left != n.left) return left < n.left;
return right < n.right;
}
};
node Nodes[maxn];
int cnt;
map<node, int> m;
int build_tree(){
int n = ++cnt; // 从1开始
node &u = Nodes[n]; // 取出一个节点
u.left = u.right = -1;
u.str = ""; u.hash = 0;
while(isalpha(*p)){
u.hash = u.hash * 27 + (*p-'a'+1);
u.str.push_back(*p);
p++;
}
if(*p == '('){ // (L, R)
p++; //越过(
u.left = build_tree();
p++;
u.right = build_tree();
p++;
}
if(m.count(u)){
cnt--;
return m[u];
}
return m[u] = n;
}
void print(int root){
if(done[root]){
printf("%d", root);
}else{
done[root] = 1;
printf("%s", Nodes[root].str.c_str());
if(Nodes[root].left!=-1){
putchar('(');
print(Nodes[root].left);
putchar(',');
print(Nodes[root].right);
putchar(')');
}
}
}
int main(){
#ifdef LOCAL
freopen("1.in", "r", stdin);
#endif
int T;
scanf("%d", &T);
while(T--){
memset(done, 0, sizeof(done));
scanf("%s", buf);
cnt = 0;
p = buf;
m.clear();
int root = build_tree();
print(root);
putchar('\n');
}
return 0;
}