Square
Time Limit: 1000 MS Memory Limit: 32768 K
Description
You are given four points, determine whether they can form a square in a two-dimensional plane. Note the area of the square must be positive.
Input
There are multiple test cases.
Each test case is a single line containing 8 integers x1 y1 x2 y2 x3 y3 x4 y4, which are the coordinates of the four points. All integers in the input are in the range of [−109 , 109 ].
Output
For each test case, output a single line containing “YES” or “NO”.
Sample Input
0 0 0 1 1 1 1 0
Sample Output
YES
Source
“尚学堂杯”2015级程序设计竞赛(11月)正式赛
题意
给你四个点,判断能否组成一个正方形。
思路
正方形的对角线相互垂直且相等,我们只要写程序验证这两点就可以了。
由于四个点的顺序不确定,所以我们要一一尝试,对于四个点,对角线的情况也就只有三种,暴力求出相应的向量然后用向量的只是全部判断一遍就可以了。
坑点
对角线有可能长度为零,判断的时候如果向量出现长度为零直接false掉。
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef struct
{
double x,y;
}aim;
aim find_xiangliang(aim a,aim b)///找到对角线的向量
{
aim temp;
temp.x = a.x-b.x;
temp.y = a.y-b.y;
return temp;
}
bool judge(aim a,aim b)///对角线是否垂直,不垂直当然不是正方形啦
{
return a.x*b.x+a.y*b.y==0;
}
bool changduxiangdeng(aim a,aim b)
{
if(a.x*a.x+a.y*a.y==0||b.x*b.x+b.y*b.y==0) return false;
///长度为零是不可能正方形。
return (a.x*a.x+a.y*a.y)==(b.x*b.x+b.y*b.y);
///对角线长度不等当然不是正方形啦
}
void solve(void)
{
aim A,B,C,D;
while(cin>>A.x>>A.y>>B.x>>B.y>>C.x>>C.y>>D.x>>D.y)
{
aim AB = find_xiangliang(A,B);
aim CD = find_xiangliang(C,D);
if(judge(AB,CD)&&changduxiangdeng(AB,CD)){
cout<<"YES"<<endl;
continue;
}
aim AC = find_xiangliang(A,C);
aim BD = find_xiangliang(B,D);
if(judge(AC,BD)&&changduxiangdeng(AC,BD)){
cout<<"YES"<<endl;
continue;
}
aim AD = find_xiangliang(A,D);
aim BC = find_xiangliang(B,C);
if(judge(AD,BC)&&changduxiangdeng(AD,BC)){
cout<<"YES"<<endl;
continue;
}
cout<<"NO"<<endl;
}
}
int main(void)
{
solve();
return 0;
}