知识点:
已知四个点,怎么判断这四个点组成的四边形是不是正方形;
解:分别求出四个点两两之间的距离,如果其中四条边的距离一样,而且另外两条边的距离也一样,则可以证明,这四个点组成的四边形是正方形,反之,则不是正方形。
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <sstream> #include <map> #include <set> #include <queue> #include <stdlib.h> using namespace std; typedef long long ll; struct point { int x; int y; }; bool cmp(point a, point b) //先按照x从小到大排序,再按照y从小到大排序 { if (a.x != b.x) return a.x < b.x; return a.y < b.y; } int getLen(point a, point b) //获取两个点之间的长度的平方 { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } bool judge(point a[]) { sort(a, a + 4, cmp); int s[10]; s[1]=getLen(a[0], a[1]); s[2]=getLen(a[0], a[2]); s[3]=getLen(a[0], a[3]); s[4]=getLen(a[1], a[2]); s[5]=getLen(a[1], a[3]); s[6]=getLen(a[2], a[3]); sort(s+1,s+1+6); if(s[1]==s[4]&&s[5]==s[6]) { return true; } return false; } int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; void init(point a[], point b[]) { for(int i = 0; i < 4; i++) { b[i].x = a[i].x; b[i].y = a[i].y; } } bool judge2(point a[]) //对每个点进行四次变化,按照第一次判断那样进行判断,只要有一次满足条件,就可以是“hai xing" { for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { point b[4]; init(a, b); //把a的值赋给b b[i].x += dx[j]; b[i].y += dy[j]; if(judge(b)) return true; } } return false; } int main() { point a[4]; for(int i = 0; i < 4; i++) cin >> a[i].x >> a[i].y; if(judge(a)) cout << "wen" << endl; else if(judge2(a)) cout << "hai xing" << endl; else cout << "wo jue de bu xing" << endl; return 0; }