← 返回 goldmansachs 的题目列表Largest Tree in a Forest
类型:online_judge
Problem: Largest Tree in a Forest
You are given a dictionary/mapping child -> parent, representing parent-child relationships in a forest. Find the root node ID of the tree with the largest number of nodes.
If multiple trees tie for the largest size, return the smallest root node ID among them.
A root is a node that has no parent, meaning it appears in the parent set but does not appear in the child set.
Example
Mapping:
{1: 2, 3: 8}
This means:
Node 1's parent is 2.
Node 3's parent is 8.
The forest contains two trees: 2 -> 1 and 8 -> 3. Both have size 2, so return the smaller root ID:
2
Input Format
The first line contains an integer n, the number of child -> parent relations.
The next n lines each contain two integers:
child parent
meaning parent is the parent of child.
Output Format
Print one integer: the root node ID of the largest tree.
If n = 0, there is no node information, so print -1.
Constraints and Assumptions
0 <= n <= 100000
Node IDs are integers in [-10^9, 10^9].
The input forms a valid forest:
There are no cycles.
Each child has at most one parent.
Only nodes appearing in the input relations are counted; isolated nodes that do not appear in the input are unknown and should not be considered.
Sample Input
2
1 2
3 8
Sample Output
2
Example
Input
2
1 2
3 8
Output
2