博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CF-29D - Ant on the Tree(DFS+路径保存回扫)
阅读量:4561 次
发布时间:2019-06-08

本文共 2413 字,大约阅读时间需要 8 分钟。

D - Ant on the Tree
Crawling in process...
Crawling failed
Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u

Description

Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.

An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.

The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.

Input

The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.

Output

If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.

Sample Input

Input
31 22 33
Output
1 2 3 2 1
Input
61 21 32 44 54 65 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
61 21 32 44 54 65 3 6
Output
-1

思路:先DFS一遍存路径,然后,在去找按叶子节点遍历的路径。

#include
#include
#include
#include
#include
#include
using namespace std;const int mm=310;int f[mm],ff[mm],q[mm];vector
g[mm],p;int n;void dfs(int u,int fa){ f[u]=fa;///存路径 for(int i=0;i
0){ff[v]=k;q[k++]=v;v=f[v];}///从v开始回找记录 while(u>0)///有解 { if(ff[u]>0)///从u开始到v有路径 { for(int i=ff[u]-1;i>=0;i--)p.push_back(q[i]); break; } ///如果当前u到v没路径,继续下走 u=f[u]; p.push_back(u); }}int main(){ while(cin>>n) { int a,b; p.clear(); for(int i=0;i
>a>>b;g[a].push_back(b);g[b].push_back(a); } dfs(1,-1);///遍历一遍,存遍历路径 //cout<<"yes"; int u=1,v; for(int i=2;i<=n;i++) if(g[i].size()==1) { int z;cin>>z; add(u,z);u=z; } ///cout<<'U'<
<

转载于:https://www.cnblogs.com/nealgavin/archive/2013/02/08/3206156.html

你可能感兴趣的文章
memset函数具体说明
查看>>
经常使用的android弹出对话框
查看>>
确保新站自身站点设计的合理性的六大注意点
查看>>
1033. 旧键盘打字(20)
查看>>
asp编程实例:ASP编程中20个非常有用的例子
查看>>
uva 11300(代数分析)
查看>>
python求线性回归斜率
查看>>
AVR汇编初探之二《AVR的指令与汇编系统》
查看>>
opencv: 基本知识(二);
查看>>
HDU 1096 A+B for Input-Output Practice (VIII)
查看>>
HDU 1076 An Easy Task
查看>>
Qt 地址薄 (二) 添加地址
查看>>
第12课 - 自动生成依赖关系(中)
查看>>
SVN简明课程
查看>>
《剑指offer》---顺时针打印矩阵
查看>>
腾讯面试总结
查看>>
oracle约束
查看>>
苹果开发者中心 - 信鸽推送
查看>>
九个uname命令获取Linux系统详情的实例
查看>>
django-ajax
查看>>