a500中等最小可放頂端與耐心排序

CPE:Containers (UVa 1062)

每次選不小於新字母的最小堆頂,減少堆數。

前往題目練習 →回報教學錯誤時間 O(L log S),空間 O(S),S≤26。

解題思路

新貨櫃x只能放在頂端字母≥x的堆,因為到貨由下往上放,最後由上往下必須非遞減。把各堆頂保持排序,用lower_bound找第一個≥x的位置並替換成x;若不存在,才新增一堆。相等字母能疊在一起。

選最小可行頂端會保留更大的頂端,讓未來較大的字母還有位置可放。更形式化地,這些頂端也是各長度嚴格遞增子序列的最小尾值;長度k的嚴格遞增到貨序列不能共用一個非遞增堆,給出k堆下界,而貪心恰使用這麼多堆。因此堆數最少。讀到end停止,輸出Case x: y。

Step-by-step animation

示意:ABCA

回報動畫錯誤
步驟 1 / 3

處理A、B

A堆頂不能接B,因此建立第二堆。

A
B
已處理
2
堆數
2

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    string s;
    int tc = 0;
    while (cin >> s && s != "end") {
        vector<char> tops;
        for (char c : s) {
            auto it = lower_bound(tops.begin(), tops.end(), c);
            if (it == tops.end())
                tops.push_back(c);
            else
                *it = c;
        }
        cout << "Case " << ++tc << ": " << tops.size() << '\n';
    }
}

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

更多