队列是用来保存遍历节点的顺序的,而栈保存的是当前遍历到的节点的父节点
模拟的过程:http://acm.hdu.edu.cn/showproblem.php?pid=4041
1):模拟过程一遍给节点名字编号;2):当遇到 '(' 时,表示当前节点有子节点,所以把当前节点同时压入栈,和队列;
3):当遇到 ')' 时,表示当前父节点的所有子节点已经遍历完,所以将当前节点压入队列,当然要再次访问父节点,所以将当前父节点也压入队列,而且,要弹出栈;当然,这时还要考虑一个问题:就是 ')'前面是否也为一个 ')',若是,则不需要将当前节点压入队列,因为已经压入过了。但是仍然是需要将栈顶压入的,即要回到父亲的父亲;
4):当遇到 ',' 时,表示遍历到了一个叶节点,将当前节点压入队列,要再次访问父节点;同上,此时还要考虑一个问题,就是','前面是否为一个‘)’,若是,则不需要将当前节点压入队列,同样,也是因为压入过了;
/*
Pro: 0
Sol:
date:
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
#include <cmath>
#include <queue>
#include <set>
#include <vector>
using namespace std;
char str[1000010],tmp[15];
char name[50010][12];
void solve(){
stack <int> ss;
queue <int> qq;
scanf("%s",str);
int len = strlen(str); int j = 0, people = 0;
for(int i = 0; i <= len;i ++){
if(str[i] >= 'a' && str[i] <= 'z'){
tmp[j ++] = str[i];
}else{
if(j != 0 || str[j] == '\0'){
tmp[j ++] = '\0';
strcpy(name[people ++],tmp);
j = 0;
}
if(str[i] == '('){
ss.push(people);
qq.push(people);
}else if(str[i] == ','){
if(str[i - 1] != ')'){
qq.push(people);
}
qq.push(ss.top());
}else if(str[i] == ')'){
if(str[i - 1] != ')'){
qq.push(people);
}//从这个点回到父亲节点
qq.push(ss.top());//回到父亲节点
ss.pop();
}
}
}
printf("%d\n",people);
for(int i = 0; i < people; i ++)
printf("%s\n",name[i]);
if(qq.size() == 1) return ;
while(!qq.empty()){
printf("%d ",qq.front());
qq.pop();
printf("%d\n",qq.front());
if(qq.size() == 1) break;
}
}
int main(){
int t; scanf("%d",&t);
for(int ca = 1; ca <= t; ca ++){
solve();
puts("");
}
return 0;
}