Problem Description
Description
985 gives you a “tree” and its root node. He asks you to first determine whether it is a tree, and then he wants to know the number of “crown princes” of each node and its parent (for the root, output itself).
“Crown prince” criteria:
- If x is a child node of y, then x is a “crown prince” of y;
- If x is a “crown prince” of y and y is a “crown prince” of z, then x is a “crown prince” of z.
Input
The first line contains an integer t, representing t test cases.
For each test case, the first line contains two integers n and root, representing the number of nodes in the tree and the root node index, respectively.
The next n-1 lines each contain two integers u and v, representing a tree edge between node u and node v.
Note: 1 <= t <= 20, 1 <= n <= 1e4, 1 <= root <= n, 1 <= u, v <= n.
Output
For each test case, if the given “tree” is invalid, just output NO; otherwise output YES, and then output two lines:
The first line outputs n integers representing the number of “crown princes” of each node,
The second line outputs n integers representing the parent node index of each node.
The output order is from 1 to n, with one space between every two numbers, and no space after the last number.
Sample Input
| |
Sample Output
| |
Problem Analysis
-.- The problem that proves I am not cut out for competitions
Yu Shen calls it a sign-in problem
Actually, the knowledge points involved are not complicated either
DFS, Union-Find, Adjacency List
DFS is used to recursively find the next node
Union-Find is used to update the node depth and parent information
Adjacency List is used to optimize the data structure
- Read the input and store it in the adjacency list
- Start from root and DFS to the next node
- Using the Union-Find idea, set the parent of the next node to this node
Finally, use the find function to update the root’s depth
| |
Problem address: ZZULI [1900] 985’s “Tree” Problem