解題思路
將每個矩形兩邊排序為短邊、長邊。若可透過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
#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';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。