题目:给一棵树的BFS,DFS的遍历序列,求这棵树每个结点的子结点。
思路:(看了无数大佬们的题解,才想明白一些问题)
这个题考察了对BFS、DFS遍历的理解。
设定BFS[i]来表示结点i在BFS中的出现下标。如果BFS[u] + 1 < BFS[v]说明结点v在BFS序列中不紧贴着u,且在u后部,则v一定是u的子结点。
DFS序列是到叶结点才返回上一层的。
详情见代码。
#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<sstream>
#include<map>
#include<stack>
#include<queue>
#include<set>
#include<string>
using namespace std;
int n,BFS_list[1001],Position[1001];
vector<int> son[1001];
int main(){
while(scanf("%d",&n)!=EOF){
for(int i = 1;i<=n;i++){
scanf("%d",&BFS_list[i]);
Position[BFS_list[i]] = i; //保存结点在BFS中的位置
son[BFS_list[i]].clear();
}
int x,root;
scanf("%d",&root);
stack<int> save;
save.push(root);
for(int i = 2;i<=n;i++){
scanf("%d",&x);
int Wait_To_Explore;
while(true){
Wait_To_Explore = save.top(); //准备找儿子的结点
if(Wait_To_Explore == root||Position[Wait_To_Explore] + 1 < Position[x]){//如果(Wait_To_Explore为根节点) 或 (x点在BFS序列中不紧贴,且在 Wait_To_Explore 后,则x为其子结点)
son[Wait_To_Explore].push_back(x);
save.push(x);//当前x入栈,进入下一次被找儿子的队伍中
break;
}else{
save.pop();//如果当前Wait_To_Explore不满足上述条件,则说明x不是Wait_To_Explore的子结点,应是Wait_To_Explore父(或 祖父...Root)结点的其他子结点。则可以说明当前的Wait_To_Explore已经是树叶了,DFS已经完成了对其的拓展,则其出栈。
}
}
}
for(int i = 1;i<=n;i++){
printf("%d:",i);
sort(son[i].begin(),son[i].end());
for(int j = 0;j<son[i].size();j++){
printf(" %d",son[i][j]);
}
printf("\n");
}
}
return 0;
}