习题6-11 树重建 UVa 10410 *
2015-10-01 19:01
309 查看
题意:输入n节点树的bfs序列和dfs序列。输出每个节点的子节点列表,其中输入序列是这样生成的:当一个节点被扩展时,其所有子节点应该按照编号从小到大的顺序被访问。
分析:又没写出来,还是太菜了。看到题解就立马明白了,先放一下,以后再看看。
#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;
}
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;
}
相关文章推荐
- Python连接mysql数据库
- CodeForces 2A Winner(CodeForces的题意总是那么难理解)——Codeforces Beta Round #2
- 递归求解数组的和 Java实现
- 数组中只出现一次的数字(剑指offer)思维有点巧
- Android系统自带分享功能的实现(可同时分享文字和图片)
- 2015弱校联盟(1) - E. Rectangle
- 2015弱校联盟(1) - E. Rectangle
- vs开发调用窗体的方法
- RBAC用户角色权限设计方案
- 桶排序——PowerShell版
- innodb 优化
- 复制构造函数跟赋值构造函数的区别
- Linux常用命令
- 使用BFS,在二维地图中,寻求特定走法的最短距离。
- 面试算法题
- IOS中Json解析的四种方法
- Mysql入门到精通数据表的操作
- 一个设置hibernate 延迟的加载的过滤器
- Aizu 2304 Reverse Roads(无向流)
- 转载:iOS开发的一些奇巧淫技