UVa 10410树重建

时间:2024-04-25 15:34:00

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1351

题意:给出bfs和dfs序列,输出每个结点的子节点。

遍历dfs序列,如果当前访问元素为v,它的前面的元素为u,那么在bfs序列中,如果u后面的那个元素不为v的话,那么v肯定是u的子序列,如果为1的话,则v是u的兄弟结点。

 #include<iostream>
#include<vector>
#include<stack>
using namespace std; vector<int> treechild[];
stack<int> sta;
int order[]; int main()
{
int n, x, i;
while (cin >> n && n)
{
for (i = ; i <= n; i++)
{
cin >> x;
order[x] = i;
treechild[i].clear();
}
int root;
cin >> root;
sta.push(root);
for (i = ; i < n; i++)
{
cin >> x;
for (;;)
{
int v = sta.top();
if (v == root || order[v] + < order[x])
{
treechild[v].push_back(x);
sta.push(x);
break;
}
else
sta.pop();
}
}
for (i = ; i <= n; i++)
{
vector<int>::iterator it = treechild[i].begin();
cout << i << ":";
for (; it != treechild[i].end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
}
return ;
}