【暑假】[基本数据结构]根据BFS与DFS确定树
来源:互联网 发布:udp端口号范围 编辑:程序博客网 时间:2024/05/17 23:11
UVa10410 Tree Reconstruction
算法:根据BFS构造pos数组以区分关系,在此基础上对DFS序列操作。注:栈中存父结点,栈顶是最优先的父结点。
代码如下:
1 #include<cstdio> 2 #include<vector> 3 #include<stack> 4 #define FOR(a,b,c) for(int a=(b);a<(c);a++) 5 using namespace std; 6 7 const int maxn= 1000 + 10; 8 9 int pos[maxn]; //BFS中的位置关系 10 vector<int> G[maxn];11 12 int main(){13 int n;14 while(scanf("%d",&n)==1){15 int x;16 FOR(i,1,n+1){17 scanf("%d",&x);18 pos[x]=i;19 G[i].clear(); //G_clear20 }21 int root;22 scanf("%d",&root);23 stack<int> sta; sta.push(root);24 int v;25 FOR(i,1,n){26 scanf("%d",&v);27 for(;;){28 int u=sta.top();29 if(u==root || pos[u]+1<pos[v]){ //u是v的父结点 30 sta.push(v);31 G[u].push_back(v);32 break; //直到找到父结点 33 }34 else //u和v是兄弟 返回到u的父结点 35 sta.pop();36 }37 }38 FOR(u,1,n+1){39 printf("%d:",u);40 FOR(j,0,G[u].size()) printf(" %d",G[u][j]);41 printf("\n");42 }43 }44 return 0;45 }
0 0
- 【暑假】[基本数据结构]根据BFS与DFS确定树
- 【暑假】[基本数据结构]根据in_order与post_order构树
- 《数据结构》C++代码 BFS与DFS
- 数据结构基础(21) --DFS与BFS
- 数据结构基础(21) --DFS与BFS
- 数据结构之DFS与BFS实现
- 暑假集训 又见dfs和bfs
- 数据结构与算法之DFS/BFS解决扫雷问题<十五>
- 数据结构----BFS和DFS详解
- 数据结构 邻接矩阵的BFS DFS
- 【数据结构作业 链表 + BFS + DFS】
- BFS 与 DFS
- bfs与dfs
- DFS与BFS
- DFS与BFS
- dfs与bfs实现
- bfs与dfs
- 【图】BFS与DFS
- Struts2使用MethodFilterInterceptor来实现方法拦截器
- ubuntu9.10使用apt-get时找不到下载源问题
- c++Primer5,类设计者的工具
- CAGradientLayer基本使用方法
- 【暑假】[网络流]网络流知识总结
- 【暑假】[基本数据结构]根据BFS与DFS确定树
- 【暑假】[基本数据结构]根据in_order与post_order构树
- 【暑假】[基本数据结构]基本的数据结构知识点总结梳理
- 初学者关于ztree的浅谈
- 【暑假】[实用数据结构]动态连续和查询问题
- 【暑假】[实用数据结构]范围最小值问题(RMQ)
- 【暑假】[实用数据结构]动态范围查询问题
- Maven Checkstyle Plugin集成
- 【暑假】[实用数据结构]UVa11995 I Can Guess the Data Structure!