#C6348. Balanced Roots Tree Rearrangement
Balanced Roots Tree Rearrangement
Balanced Roots Tree Rearrangement
You are given an undirected tree with N nodes and exactly N-1 edges. Your task is to determine whether it is possible to rearrange the tree so that it becomes a Balanced Roots Tree.
A tree is defined as a Balanced Roots Tree if for every non‐leaf node, the heights (i.e. the maximum distance from that child to any leaf in its subtree) of all its subtrees are equal. If the tree contains only one node, it is considered balanced.
If the tree satisfies the condition, output YES
on the first line and then print the new parent-child relationships in breadth-first search (BFS) order from node 1. For each edge, print the parent and the child separated by a space on a new line.
If the tree cannot be rearranged to meet the criteria, output just NO
.
Note: When checking the balance for each node, if a node has one child, consider it balanced (since there is only one subtree to compare).
inputFormat
The input is provided via standard input (stdin) and has the following format:
- The first line contains a single integer N, the number of nodes.
- The next N-1 lines each contain two integers u and v (separated by space) representing an edge between nodes u and v.
outputFormat
If the tree can be rearranged into a Balanced Roots Tree (i.e. for every non‐leaf node, all the subtrees of its children have the same height), output YES
on the first line followed by the list of parent-child pairs in BFS order (one pair per line, parent and child separated by a space). If it cannot be rearranged, output NO
only.
Output is written to standard output (stdout).
## sample7
1 2
1 3
2 4
2 5
3 6
3 7
YES
1 2
1 3
2 4
2 5
3 6
3 7
</p>