QOJ.ac

QOJ

時間限制: 1.0 s 記憶體限制: 256 MB 總分: 100 可 Hack ✓

#14099. 神奇的树

统计

考虑一棵无向树。以下算法用于构建该树的后序遍历:

fun dfs(v):
    mark v as used
    for u in neighbours(v):
        if u is not used:
            dfs(u)
    append v to order

后序遍历的结果将存储在列表 order 中。

你可以自由选择每个顶点的邻居遍历顺序以及起始顶点。你能得到的字典序最小的 order 是什么?

输入格式

输入的第一行包含一个整数 $T$ ($1 \le T \le 10^5$) — 需要处理的测试用例数量。接下来是测试用例的描述。

每个测试用例的第一行包含一个整数 $n$ ($2 \le n \le 2 \cdot 10^5$) — 树中顶点的数量。

接下来的 $n - 1$ 行中,第 $i$ 行包含两个整数 $u_i, v_i$ ($1 \le u_i, v_i \le n, u_i \ne v_i$),表示树中存在一条无向边 $(u_i, v_i)$。保证给定的图是一棵树。

在一个测试文件中,所有测试用例的 $n$ 之和不超过 $2 \cdot 10^5$。

输出格式

对于每个测试用例,在单独的一行中输出能得到的字典序最小的遍历顺序。

样例

输入样例 1

3
3
1 3
3 2
3
2 1
1 3
7
1 2
1 3
2 4
2 5
3 6
3 7

输出样例 1

1 2 3
2 1 3
4 5 2 1 6 3 7

说明

第一个测试用例如下所示:

从顶点 1 开始,我们只能得到顺序 2 3 1。从顶点 2 开始,我们只能得到顺序 1 3 2。从顶点 3 开始,我们可以得到两种顺序:1 2 3 和 2 1 3。这四种顺序中字典序最小的是 1 2 3。

第二个测试用例如下所示:

从顶点 1 开始,我们可以得到两种顺序:2 3 1 和 3 2 1。从顶点 2 开始,我们只能得到顺序 3 1 2。从顶点 3 开始,我们只能得到顺序 2 1 3。这四种顺序中字典序最小的是 2 1 3。

第三个测试用例如下所示:

字典序最小的顺序是 4 5 2 1 6 3 7,可以通过从节点 7 开始得到。

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.