← 返回 optiver 的题目列表Giving Tree of Errors: Validate Parent-Child Pairs and Output Lexicographically Smallest S-Expression
类型:online_judge
You are given an unordered list of parent-child pairs describing edges of a binary tree. Each edge is formatted as (P,C) meaning P is the parent of C. Node names are uppercase letters A-Z.
Tasks:
Determine whether the edges form a valid binary tree.
If invalid, output exactly one error code E1~E5 according to the given priority.
If valid, build the tree and output the lexicographically smallest S-Expression. For each node, output (X<left><right>), ordering children alphabetically; if a node has only one child, it is placed in the left position.
Validity rules (common OA variant)
A parent may have at most two children.
Duplicate edges are not allowed.
A child may have at most one parent.
There must be exactly one root (exactly one node with in-degree 0) and the structure must be connected as a tree (not a forest).
No cycles.
Input (suggested)
One line containing pairs separated by spaces, e.g.:
(A,B) (A,C) (B,D)
Output
If invalid: print E1/E2/E3/E4/E5.
If valid: print the lexicographically smallest S-Expression.
Examples
Input:
(A,B) (A,C) (B,D)
Output:
(A(B(D))(C))
Input:
(A,B) (A,B)
Output:
E2
Input:
(A,B) (C,D)
Output:
E4
Example
Input
(A,B) (A,C) (B,D)
Output
(A(B(D))(C))