a612簡單邊長排序與嚴格多邊形不等式

CPE:Behold My Quadrangle (UVa 11455)

依分類優先順序判斷四條邊能組成的形狀。

前往題目練習 →回報教學錯誤每筆時間、空間 O(1)。

解題思路

排序後 a≤b≤c≤d。四邊相等就可組成正方形;否則 a=b 且 c=d 可組成長方形。這兩種判斷必須先做,因為它們也都是一般四邊形。

剩餘情況有非退化四邊形的充要條件是 a+b+c>d:最長邊必須小於其餘三邊總和。等號只能攤平成直線,應輸出 banana。題敘稱為正邊長,但邊界文字提到 0,程式保守地將非正邊分類為 banana。加總使用 64 位元,避免三個接近 2^30 的邊溢位。

Step-by-step animation

示意:1、2、3、6

回報動畫錯誤
步驟 1 / 3

排序邊長

已是 1≤2≤3≤6。

1
2
3
6
最長邊
6

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        long long a[4];
        for (auto &x : a)
            cin >> x;
        sort(a, a + 4);
        if (a[0] <= 0)
            cout << "banana\n";
        else if (a[0] == a[3])
            cout << "square\n";
        else if (a[0] == a[1] && a[2] == a[3])
            cout << "rectangle\n";
        else if (a[0] + a[1] + a[2] > a[3])
            cout << "quadrangle\n";
        else
            cout << "banana\n";
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多