CF765E.Tree Folding

提高+/省选-

通过率:0%

时间限制:2.00s

内存限制:512MB

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length _a_0 = v, _a_1, ..., a__k, and _b_0 = v, _b_1, ..., b__k. Additionally, vertices _a_1, ..., a__k, _b_1, ..., b__k must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices _b_1, ..., b__k can be effectively erased:

Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.

万尼亚希望将一棵树最小化。他可以多次执行以下操作:选择一个顶点 vv,以及两条长度相等且仅在 vv 处相交(即不相交于其他顶点)的路径:a0=v,a1,…,aka_0 = v, a_1, \dots, a_k 和 b0=v,b1,…,bkb_0 = v, b_1, \dots, b_k;此外,顶点 a1,…,ak,b1,…,bka_1, \dots, a_k, b_1, \dots, b_k 在树中除对应路径上的相邻顶点外,不能有其他邻接点。随后,可将其中一条路径合并到另一条上,即顶点 b1,…,bkb_1, \dots, b_k 可被有效删除:

请帮助万尼亚判断:能否通过若干次上述操作将该树变为一条路径?若可以,请进一步求出所得路径的最短长度。

输入格式

The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105).

Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.

输入的第一行包含顶点数 nn(2 ≤ n ≤ 2⋅1052 \leq n \leq 2\cdot10^5)。

接下来的 n − 1n - 1 行描述树的边。每行包含两个以空格分隔的整数 uu 和 vv(1 ≤ u, v ≤ n1 \leq u, v \leq n,且 u ≠ vu \neq v),表示对应边的两个端点的下标。保证所给图是一棵树。

输出格式

If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.

如果无法获得路径,则输出 -1。否则,输出可能路径中边的最小数量。

输入输出样例

  • 输入#1

    6
    1 2
    2 3
    2 4
    4 5
    1 6

    输出#1

    3
  • 输入#2

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

    输出#2

    -1

说明/提示

In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.

It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.

在第一个样例中,合并路径 2-1-62\text{-}1\text{-}6 和 2-4-52\text{-}4\text{-}5 后得到一条包含三条边的路径。

在第二个样例中,无法执行任何操作。例如,无法合并路径 1-3-41\text{-}3\text{-}4 和 1-5-61\text{-}5\text{-}6,因为顶点 66 还有一个邻居 77,而该邻居未出现在对应的路径中。

输入解题思路,AI测评打分。不知道怎么写?

首页