b184中等

94 雲嘉區資訊學科能力競賽(2005)|矩形堆疊

將每個矩形兩邊排序為短邊、長邊。若可透過90度旋轉包含,正規化後兩邊也各自滿足大小關係。

解題思路

將每個矩形兩邊排序為短邊、長邊。若可透過90度旋轉包含,正規化後兩邊也各自滿足大小關係。

將矩形按短邊、長邊遞增排序,問題化為長邊的最長非遞減子序列。

使用upper_bound維護各長度的最小尾值;相同尺寸可疊,所以必須找嚴格大於目前值的位置替換。

時間 O(n log n),空間 O(n)。

Step-by-step animation

教學小例:旋轉正規化與非嚴格LIS

回報動畫錯誤
步驟 1 / 3

矩形5×1、2×3、3×2

正規化為(1,5),(2,3),(2,3)

正規化為(1,5),(2,3),(2,3)
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<pair<int, int>> a(n);
        for (auto &[x, y] : a) {
            cin >> x >> y;
            if (x > y)
                swap(x, y);
        }
        sort(a.begin(), a.end());
        vector<int> d;
        for (auto [x, y] : a) {
            auto it = upper_bound(d.begin(), d.end(), y);
            if (it == d.end())
                d.push_back(y);
            else
                *it = y;
        }
        cout << d.size() << '\n';
    }
}

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

更多