解題思路
把每座塔的頂端大小由小到大儲存。新方塊 x 必須放在嚴格大於 x 的塔頂上,因此二分找第一個 >x 的位置;找到就替換成 x,找不到才開新塔。
若其他合法安排把 x 放在更大的頂端上,交換兩座塔的後續安排,可以改放到最小可承接頂端;這留下的較大頂端只會更容易承接未來方塊。等價地,貪心後排序塔頂逐項不大於任何同塔數方案,歸納可知需要新塔時其他方案也無法避免。
時間 O(n log n),空間 O(n),n≤2×10^5。Python bisect_right 及塔頂列表 O(n),全量輸入緩衝 O(n)。
Step-by-step animation
以下為獨立教學例子;每一步呈現實際狀態。
步驟 1 / 3
步驟 1:加入 3
加入 3
3
- 塔數
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll P = 1000000007;
ll pw(ll a, ll b, ll p = P) {
ll r = 1;
for (; b; b >>= 1, a = a * a % p)
if (b & 1)
r = r * a % p;
return r;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, x;
cin >> n;
vector<int> t;
while (n--) {
cin >> x;
auto it = upper_bound(t.begin(), t.end(), x);
if (it == t.end())
t.push_back(x);
else
*it = x;
}
cout << t.size() << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。