#include <iostream>
#include <bits/stdc++.h>
#define maxn 50005
using namespace std;
string s;
int k,u;//u是单词的id
struct tree
{
string tmp;
int lch,rch;
bool operator < (const tree & a) const
{
if(tmp!=a.tmp) return tmp<a.tmp;
else if(lch!=a.lch) return lch<a.lch;
else return rch<a.rch;
}
};
map<int,tree>node;
map<tree,int>num;
int flag[maxn];
int build()
{
string cur;
while(isalpha(s[k]))
cur.push_back(s[k++]);
int id = ++u;
node[id].tmp = cur;node[id].lch = 0;node[id].rch = 0;
if(s[k]=='(')
{
k++;
node[id].lch = build();
k++;
node[id].rch = build();
k++;
}
tree t = node[id];
if(num[t])
{
u--;
return num[t];
}
else
{
return num[t] = id;
}
}
void dfs(int k)
{
if(flag[k])
{
cout<<k;
return;
}
flag[k] = 1;
cout<<node[k].tmp;
if(node[k].lch)
{
cout<<"(";
dfs(node[k].lch);
cout<<",";
dfs(node[k].rch);
cout<<")";
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>s;
k = 0;u = 0;
num.clear();node.clear();
memset(flag,0,sizeof(flag));
build();
dfs(1);
cout<<endl;
}
return 0;
}
/**
3
this(is(a,tiny),tree)
a(b(f(a,a),b(f(a,a),f)),f(b(f(a,a),b(f(a,a),f)),f))
z(zz(zzzz(zz,z),zzzz(zz,z)),zzzz(zz(zzzz(zz,z),zzzz(zz,z)),z))
**/