給定平面上四個點(座標為整數,範圍 ±10⁸),判斷它們能否構成一個正方形。能則輸出 "Yes",否則 "No"。多測試案例,T ≤ 10⁵。
四邊形為正方形的充要條件(任一):
d[6]。d。d[0] > 0 && d[0]==d[1] && d[1]==d[2] && d[2]==d[3] && // 四邊相等
d[4]==d[5] && // 對角線相等
d[4] == 2 * d[0] // 畢達哥拉斯關係此法無需判斷點序、無浮點誤差、邏輯極簡。
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Pt { ll x, y; };
ll dist2(const Pt& a, const Pt& b) {
ll dx = a.x - b.x, dy = a.y - b.y;
return dx*dx + dy*dy;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T; cin >> T;
while (T--) {
Pt p[4];
for (int i = 0; i < 4; ++i) cin >> p[i].x >> p[i].y;
ll d[6]; int cnt = 0;
for (int i = 0; i < 4; ++i)
for (int j = i+1; j < 4; ++j)
d[cnt++] = dist2(p[i], p[j]);
sort(d, d+6);
bool ok = (d[0] > 0) &&
(d[0] == d[1] && d[1] == d[2] && d[2] == d[3]) &&
(d[4] == d[5]) &&
(d[4] == 2 * d[0]);
cout << (ok ? "Yes" : "No") << '\n';
}
return 0;
}
sqrt 計算邊長再比較,導致精度丟失 WA。永遠用距離平方整數運算。判斷四點是否構成正方形,**距離平方排序法** 是最簡潔、最穩健、最不易出錯的做法。核心洞見:正方形的 6 條兩兩距離中,必有 4 條相等的邊長、2 條相等的對角線,且滿足 對角線² = 2 × 邊長²。拒絕浮點,拒絕複雜點序邏輯,一行判斷搞定一切。