您的位置:首页 > 其它

习题6-11 树重建 UVa 10410 *

2015-10-01 19:01 309 查看
题意:输入n节点树的bfs序列和dfs序列。输出每个节点的子节点列表,其中输入序列是这样生成的:当一个节点被扩展时,其所有子节点应该按照编号从小到大的顺序被访问。

Sample Input

8
4 3 5 1 2 8 7 6
4 3 1 7 2 6 5 8

Sample Output

1: 7
2: 6
3: 1 2
4: 3 5
5: 8
6:
7:
8:

分析:又没写出来,还是太菜了。看到题解就立马明白了,先放一下,以后再看看。

#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int maxn=1010;
vector<int> tree[maxn];
int pos[maxn],dfs[maxn],n;
int main()
{
freopen("f.txt","r",stdin);
while(~scanf("%d",&n)){
memset(pos,0,sizeof(pos));
memset(dfs,0,sizeof(dfs));
int k,p,q=0;
for(int i=0;i<n;i++){
scanf("%d",&k);
pos[k]=i;
tree[i].clear();
}
scanf("%d",&dfs[0]);
for(int i=1;i<n;i++){
scanf("%d",&p);
while(q&&pos[p]<=pos[dfs[q]]+1)--q;
tree[dfs[q]-1].push_back(p);
dfs[++q]=p;
}
for(int i=0;i<n;i++){
printf("%d:",i+1);
for(int j=0;j<tree[i].size();j++){
printf(" %d",tree[i][j]);
}
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: