After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.
The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend.
Each of the following n lines contains two integers xi and yi ( - 1000 ≤ xi, yi ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.
It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.
Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1.
2 0 0 1 1
1
1 1 1
-1
In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.
In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
题目大意:已知一个矩形的n个顶点坐标(n<=4),且这n个顶点组成的边平行坐标轴。问通过这n个点能否确定唯一的一个矩形。
如果可以输出其面积,否则输出-1.
解题思路:首先对坐标按横坐标从小到大排一下序,如果横坐标相等,则按纵坐标从小到大排序;然后分四种情况讨论(即n=1,n=2,n=3,n=4);
写地有点乱,
AC代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int x,y;
}a[5];
bool cmp(struct node v,struct node u)
{
if(v.x!=u.x) return (v.x<u.x);
else return (v.y<u.y);
}
int main()
{
int n,i,j,flag=1,s;
memset(a,0,sizeof(a));
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+n+1,cmp); //排序
if(n==1) flag=0; //已知顶点为1,一定不能确定唯一的矩形,flag=0;
else if(n==2)
{
if(a[1].x==a[2].x||a[1].y==a[2].y) flag=0; //n为2,若其并不是对角线上的两点,flag=0;
else s=(a[2].y-a[1].y)*(a[2].x-a[1].x);
}
else if(n==3)
{
if(a[2].x!=a[3].x&&a[2].y!=a[3].y&&a[1].x==a[2].x&&a[1].y==a[3].y) //2和3是对角线上的两点
s=(a[3].x-a[1].x)*(a[2].y-a[1].y);
else if(a[2].x!=a[1].x&&a[1].y!=a[2].y&&a[3].y==a[1].y&&a[3].x==a[2].x) //1和2是对角线上的两点。
s=(a[3].y-a[2].y)*(a[2].x-a[1].x);
else if(a[1].x!=a[3].x&&a[1].y!=a[3].y&&((a[2].x==a[1].x&&a[2].y==a[3].y)||(a[2].x==a[3].x&&a[2].y==a[1].y)))
s=(a[3].y-a[1].y)*(a[3].x-a[1].x); //1和3是对角线上的两点
else flag=0; //否则,flag=0;
}
else if(n==4)
{
if(((a[1].x+a[4].x)==(a[2].x+a[3].x))&&((a[1].y+a[4].y)==(a[2].y+a[3].y))) //对角线对应点横坐标之和相等,纵坐标之和相等
s=(a[4].y-a[3].y)*(a[3].x-a[1].x);
else flag=0;
}
s=abs(s); //s有可能为负,所以取一下绝对值。
if(flag==1) printf("%d\n",s);
else printf("-1\n");
return 0;
}