欢迎来到起遇信息学
起遇信息学正处于上线筹建阶段,以下功能已全部开放免费体验: ✅ 完整题库浏览与代码提交评测(C / C++ / Python / Java 等) ✅ 入门到进阶的系列课程试读、作业与考试 ✅ AI 提示、AI 作业分析等智能助教功能 ✅ 赛事模拟与个人能力报告 ✅ 邮箱注册开放 ⏳ 付费课程订阅与微信/支付宝支付通道 ⏳ 手机号登录,微信扫码登录、微信公众号绑定 使用中如遇任何问题,欢迎通过页面底部 **"联系我们"** 与我们沟通。
CF1037D.Valid BFS?
Valid BFS?
The BFS algorithm is defined as follows.
- Consider an undirected graph with vertices numbered from to . Initialize as a new queue containing only vertex , mark the vertex as used.
- Extract a vertex from the head of the queue .
- Print the index of vertex .
- Iterate in arbitrary order through all such vertices that is a neighbor of and is not marked yet as used. Mark the vertex as used and insert it into the tail of the queue .
- If the queue is not empty, continue from step
2. - Otherwise finish.
Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.
In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex . The tree is an undirected graph, such that there is exactly one simple path between any two vertices.
Input
The first line contains a single integer () which denotes the number of nodes in the tree.
The following lines describe the edges of the tree. Each of them contains two integers and () — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.
The last line contains distinct integers () — the sequence to check.
Output
Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.
You can print each letter in any case (upper or lower).
Note
Both sample tests have the same tree in them.
In this tree, there are two valid BFS orderings:
- ,
- .
The ordering doesn't correspond to any valid BFS order.
Samples
4
1 2
1 3
2 4
1 2 3 4
Yes
4
1 2
1 3
2 4
1 2 4 3
No
在线编程 IDE
建议全屏模式获得最佳体验
| 进入全屏编程 | Alt+E |
| 递交评测 | Ctrl+Enter |
| 注释/取消注释 | Ctrl+/ |
| 缩放字体 | Ctrl+滚轮 |