a308困難雙維嚴格遞增鏈與同長反向排序
TOI 2022/10 潛力組:金字塔
把長寬都嚴格增加的最大木板鏈轉成 O(N log N) 的 LIS。
解題思路
由上往下觀察金字塔,木板的長與寬都要嚴格增加。先依長度遞增排序,但長度相同時依寬度遞減排序,再對寬度做嚴格遞增最長子序列。相同長度那一組的寬度不遞增,所以任何嚴格遞增寬度子序列最多挑其中一片,不會誤用同長木板。不同長度的板只要寬也增加,就符合上下關係。
維護 tails[t]:目前長度 t+1 的合法寬度遞增子序列,能達到的最小結尾寬度。對新寬度 w,以 lower_bound 找第一個≥w 的位置並替換;若不存在則新增一層。較小的結尾能接納至少同樣多的後續寬度,因此替換不會失去最佳長度。用第一個≥w 而非>w,才能排除等寬堆疊;木板不旋轉,輸入的長寬角色保持固定。
Step-by-step animation
公開範例排序後:(2,3)、(3,4)、(4,3)、(5,7)
步驟 1 / 3
讀入前兩片
寬度 3、4 可形成兩層,tails=[3,4]。
(2,3)
(3,4)
(4,3)
(5,7)
- tails
- 3,4
- 最長
- 2
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pair<int, int>> a(n);
for (auto &[l, w] : a)
cin >> l >> w;
sort(a.begin(), a.end(), [](auto x, auto y) {
return x.first != y.first ? x.first < y.first : x.second > y.second;
});
vector<int> tails;
for (auto [l, w] : a) {
auto it = lower_bound(tails.begin(), tails.end(), w);
if (it == tails.end())
tails.push_back(w);
else
*it = w;
}
cout << tails.size() << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。