题目1 : Smallest Rectangle
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
You are given N 2D points P1, P2, ... PN. If there is a rectangle satisfying that its 4 vertices are in the given point set and its 4 sides are parallel to the axis we say the rectange exists.
Find the smallest exsisting rectange and output its area.
输入
The first line contains an integer N. (1 <= N <= 1000)
The following N lines each contain 2 integers Xi and Yi denoting a point (Xi, Yi). (0 <= Xi, Yi <= 1000000)
输出
Output the smallest area. If no rectangle exsists output -1.
样例输入
9 0 0 0 1 0 4 1 0 1 1 1 4 4 0 4 1 4 4
样例输出
1
把所有的点都放在哈希表里,这样可以O(1)判断一个坐标(x, y)上是不是有点。
然后枚举其中两个点,不妨设是(Xi, Yi)和(Xj, Yj),当作矩形的左上角顶点和右下角顶点。
这样我们只需判断(Xi, Yj)和(Xj, Yi)上有没有点即可判断是否构成一个矩形。如果构成矩形的化,更新当前最小面积。
总的时间复杂度是O(N^2)。
import java.util.*;
public class Main {
static class Point implements Comparable<Point> {
long x;
long y;
Point(long x, long y) {
this.x = x;
this.y = y;
}
public int hashCode()
{
return (int)((x << 20) + y);
}
public boolean equals(Object obj)
{
Point p = (Point)obj;
return x == p.x && y == p.y;
}
public int compareTo(Point o) {
if (x == o.x) {
if (y == o.y) {
return 0;
}
return y < o.y ? -1 : 1;
}
return x < o.x ? -1 : 1;
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashSet<Point> set = new HashSet<>();
ArrayList<Point> arr = new ArrayList<>();
for(int i = 0; i < n; i++) {
long x = sc.nextLong();
long y = sc.nextLong();
arr.add(new Point(x, y));
set.add(new Point(x, y));
}
Long ans = -1L;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
long x1 = arr.get(i).x;
long y1 = arr.get(i).y;
long x2 = arr.get(j).x;
long y2 = arr.get(j).y;
if (x1 == x2 || y1 == y2) {
continue;
}
if(set.contains(new Point(x1, y2)) && set.contains(new Point(x2, y1))) {
long area = Math.abs((x1 - x2) * (y1 - y2));
if (ans == -1L || area < ans) {
ans = area;
}
}
}
}
System.out.println(ans);
}
}