题意:
给你一个字符串,转化为一棵树,输出先序遍历节点的顺序;
解析:
整个串由节点名字,’(‘、’)’、’,’ 组成,遇到一个括号时,当前左括号是当前括号内节点的父节点,括号内用’,’隔开的是兄弟节点,整体就是一颗树;
用栈模拟整个串来遍历该树,用vector来保存遍历节点的顺序。模拟的过程如下:
1)当遇到字符时,建立一条路径来连接当前的栈顶和当前的编号,并把当前的编号压入栈中;
2):当遇到 ‘)’ 或者’,’时,表示当前父节点的所以子节点已经遍历完,将当前的栈顶和栈顶下一位建立路径,将栈顶pop。
AC代码
#include <cstdio>
#include <cctype>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const int N = 1000005;
char line[N];
int st[N];
struct Path {
int from, to;
Path(int _from, int _to) {
from = _from, to = _to;
}
};
string str[50005];
vector<Path> vec;
int main() {
//freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while(T--) {
scanf("%s", line);
int tot = 1, top = -1;
vec.clear();
for(int i = 0; line[i]; i++) {
if(islower(line[i])) {
vec.push_back(Path(st[top], tot));
st[++top] = tot;
str[tot] = ""; str[tot] += line[i++];
while(islower(line[i])) str[tot] += line[i++];
tot++, i--;
}else if(line[i] == ')' || line[i] == ',') {
vec.push_back(Path(st[top], st[top-1]));
top--;
}
}
printf("%d\n", tot-1);
for(int i = 1; i < tot; i++)
printf("%s\n", str[i].c_str());
for(int i = 1; i < vec.size(); i++)
printf("%d %d\n", vec[i].from, vec[i].to);
puts("");
}
return 0;
}