Rectilinear Polygon
Time limit1sMemory limit128 MB
Given n integer points, decide whether they can be the vertices of a simple rectilinear polygon, and if so output its perimeter, else -1.
- Level
Medium7 of 10
- Topics
- Geometry, Sorting, Implementation
- Solved
- No attempts yet
Problem
You are given points with integer coordinates in the plane. Determine whether it is possible to build a simple rectilinear polygon whose vertices are exactly these points.
A rectilinear polygon satisfies all of the following:
- It has at least vertices.
- Every edge is either horizontal or vertical.
- Each vertex is an endpoint of exactly one horizontal edge and exactly one vertical edge.
- It is simple: no two edges cross, other than adjacent edges meeting at a shared endpoint, and the polygon has no holes.
Every given point must be used as a vertex. If such a polygon exists, output its perimeter (the sum of the lengths of all edges); otherwise output .
Input
The first line contains an integer, the number of test cases.
Each test case begins with an integer (), the number of points, followed by pairs of integers giving the and coordinates of the points.
Output
For each test case output a single line. If a valid rectilinear polygon through the given points exists, output its perimeter as an integer; otherwise output .