Fence Planning
InterviewTime limit2sMemory limit512 MB
Connect cows into groups given moo pairs, then find the axis-aligned rectangle of smallest perimeter that fully contains one group.
- Level
Medium5 of 10
- Topics
- Union-find, Graph, Geometry, Implementation
- Solved
- No attempts yet
Problem
Farmer John has cows, conveniently numbered (). The cows have a complex social structure revolving around "moo networks": smaller groups of cows that communicate within their group but not with other groups.
Each cow is situated at a distinct location on the 2D map of the farm, and pairs of cows moo at each other. Two cows that moo at each other belong to the same moo network.
To update his farm, Farmer John wants to build a rectangular fence with its edges parallel to the and axes. Farmer John wants at least one moo network to be completely enclosed by the fence (cows on the boundary of the rectangle count as being enclosed). Find the smallest possible perimeter of a fence that satisfies this requirement. This fence may have zero width or zero height.
Input
The first line of input contains and . The next lines each contain the and coordinates of a cow (nonnegative integers of size at most ). The next lines each contain two integers and describing a moo connection between cows and . Every cow has at least one moo connection, and no connection is repeated in the input.
Output
Print the smallest perimeter of a fence satisfying Farmer John's requirements.