您的位置:首页 > 其它

UVA 12219 Common Subexpression Elimination——map

2017-10-07 11:26 288 查看
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
const int MAXN = 1e6;
struct Node {
char s[10];
int cnt, num, lch, rch;
bool operator < (const Node &temp) const {
if (num != temp.num) return num < temp.num;
if (lch != temp.lch) return lch < temp.lch;
return rch < temp.rch;
}
};
struct Tree {
Node node[MAXN];
int tot, pos;
char str[MAXN];
map<Node, int> m;
bool vis[MAXN];
void init() {
scanf("%s", str + 1);
tot = 0, pos = 1;
m.clear();
}
int build() {
int root = ++tot;
node[root].cnt = node[root].num = node[root].lch = node[root].rch = 0;
vis[root] = false;
while ('a' <= str[pos] && str[pos] <= 'z') {
node[root].s[++node[root].cnt] = str[pos];
node[root].num = node[root].num * 30 + str[pos] - 'a' + 1;
++pos;
}
if (str[pos] == '(') {
++pos; node[root].lch = build();
++pos; node[root].rch = build();
++pos;
}
int x = m[node[root]];
if (x) { --tot; return x; }
else return m[node[root]] = root;
}
void output(int root) {
if (vis[root]) printf("%d", root);
else {
vis[root] = true;
for (int i = 1; i <= node[root].cnt; i++) printf("%c", node[root].s[i]);
if (node[root].lch) {
printf("("); output(node[root].lch); printf(","); output(node[root].rch); printf(")");
}
}
}
}tree;
int main() {
int T; scanf("%d", &T);
while (T--) {
tree.init();
tree.build();
tree.output(1);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: