递归下降建树,然后对每个节点编号....一个节点该节点的hash值和左儿子的编号和右儿子的编号是唯一的....用map查询
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 800000;
struct node
{
int val, id, is;
string s;
node *ch[2];
}pool[maxn], *tail, *root;
struct point
{
int val, lson, rson;
bool operator < (const point &b) const {
if(val != b.val) return val < b.val;
if(lson != b.lson) return lson < b.lson;
return rson < b.rson;
}
};
map<point, int> mpp;
vector<int> ans;
char P[maxn];
int top, n, id;
node* newnode(int val, string s)
{
tail->val = val;
tail->ch[0] = tail->ch[1] = NULL;
tail->s.clear();
tail->s = s;
return tail++;
}
void init()
{
tail = pool;
}
node* eat()
{
string ss;
ss.clear();
int t = 0;
while(top <= n && P[top] >= 'a' && P[top] <= 'z') {
ss += P[top];
t = t * 30 + P[top] - 'a' + 1;
top++;
}
return newnode(t, ss);
}
void ate(char ch)
{
if(P[top] == ch) top++;
}
node* build()
{
if(top > n) return NULL;
node *p = eat();
if(P[top] == '(') {
ate('(');
p->ch[0] = build();
ate(',');
p->ch[1] = build();
ate(')');
}
return p;
}
void dfs(node *p)
{
point t;
t.val = p->val;
int now = ++id;
if(p->ch[0]) {
dfs(p->ch[0]);
dfs(p->ch[1]);
t.lson = p->ch[0]->id;
t.rson = p->ch[1]->id;
}
else t.lson = t.rson = -1;
if(mpp.count(t)) {
p->is = 1, p->id = mpp[t];
id--;
}
else {
p->id = mpp[t] = now;
p->is = 0;
}
}
void DFS(node *p)
{
if(p->is == 0) {
for(int i = 0; i < p->s.length(); i++) ans.push_back(-p->s[i]);
}
else ans.push_back(p->id);
if(p->ch[0] && p->is == 0) {
ans.push_back(-'(');
DFS(p->ch[0]);
ans.push_back(-',');
DFS(p->ch[1]);
ans.push_back(-')');
}
}
void work()
{
mpp.clear();
scanf("%s", P+1);
n = strlen(P+1);
top = 1;
root = build();
id = 0;
dfs(root);
ans.clear();
DFS(root);
for(int i = 0; i < ans.size(); i++) {
if(ans[i] < 0) printf("%c", -ans[i]);
else printf("%d", ans[i]);
}
printf("\n");
}
int main()
{
//freopen("data", "r", stdin);
int _;
scanf("%d", &_);
while(_--) {
init();
work();
}
return 0;
}