这是一道数据结构的水题,考查最简单的树,处理代码如下
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int M = 50005;
const int N = 1000005;
struct Node
{
char name[12];
vector<int> ve;
int id;
void init()
{
ve.clear();
}
}node[M],*root;
char str[N];
int top,k;
void sol();
void dfs(Node *r);
void travel(int x);
int main()
{
int t;
scanf("%d",&t);
for(int i = 0;i < M;i++)node[i].id = i;
while(t--)
{
scanf("%s",&str);
sol();
}
}
void sol()
{
top = k = 0;
root = &node[top++];
root->init();
int x = 0;
while(str[k]!= '(' && str[k] != ')' && str[k] != ','&&str[k])
{
root->name[x++] = str[k++];
}
root->name[x] = '\0';
if(str[k] == '(')
{
k++;
dfs(root);
}
printf("%d\n",top);
for(int i = 0;i < top;i++)
{
printf("%s\n",node[i].name);
}
travel(0);
printf("\n");
}
void dfs(Node *r)
{
if(str[k]!= '(' && str[k] != ')' && str[k] != ',' && str[k])
{
r->ve.push_back(top);
Node *p = &node[top++];
p->init();
int x = 0;
while(str[k] != ')' && str[k])
{
if(str[k] != ',' && str[k] != '(')
p->name[x++] = str[k++];
else if(str[k] == ',')
{
r->ve.push_back(top);
p->name[x] = '\0';
p = &node[top++];
p->init();
k++;
x = 0;
}
else if(str[k] == '(')
{
k++;
p->name[x] = '\0';
dfs(p);
}
}
if(str[k] == ')')
{
k++;
p->name[x] = '\0';
return;
}
p->name[x] = '\0';
}
}
void travel(int x)
{
for(int i = 0;i < node[x].ve.size();i++)
{
printf("%d %d\n",x+1,node[x].ve[i]+1);
travel(node[x].ve[i]);
printf(" %d\n",x+1);
}
if(x != 0)
printf("%d",x+1);
}