D. Reachability and Tree
Problem Statement
Let and be two distinct vertices in a directed graph. Let’s call the ordered pair good if there exists a path from vertex to vertex along the edges of the graph.
You are given an undirected tree with vertices and edges. Determine whether it is possible to assign a direction to each edge of this tree so that the number of good pairs in it is exactly . If it is possible, print any way to direct the edges resulting in exactly good pairs.
Input
The first line contains one integer — the number of test cases.
The first line of each test case contains one integer — the number of vertices in the tree.
The next lines describe the edges. The -th line contains two integers and — the vertices connected by the -th edge.
It is guaranteed that the edges in each test case form an undirected tree and that the sum of over all test cases does not exceed .
Output
For each test case, print “NO” (case-insensitive) if it is impossible to direct all edges of the tree and obtain exactly good pairs of vertices.
Otherwise, print “YES” (case-insensitive) and then print pairs of integers and separated by spaces — the edges directed from to .
The edges can be printed in any order. If there are multiple answers, output any.
Solution
The idea is to find a node with degree 2. Suppose we have with degree 2, then we can have . Then make all the other edges have length 1, and we will have good pairs. The good pairs are provided by the edges and 1 more is provided by .