a590中等交換論證與有界乘方

CPE:A Minimum Land Price (UVa 11824)

將昂貴土地提早購買,安全判斷總價是否超出預算。

前往題目練習 →回報教學錯誤排序 O(n log n),乘方最多 O(n²) 次但會提早截斷;空間 O(n)。

解題思路

年份愈晚,價格 L 的指數愈大。對 x≥y≥1 及相鄰年份 t、t+1,先買 x 的花費比先買 y 少:差值由 x^t(x−1)≥y^t(y−1) 得證。因此將 L 遞減排序,依序支付 2L^1、2L^2……就是最低總價。

預算只有 5000000,不必計算天文數字。以連乘求冪,每一步若 value>預算/L 就立刻判定超額;所有價格非負,任何單筆或累計超額都不可能挽回。即使已知超額,仍須先讀完該組的 0 哨兵,避免下一組錯位。

Step-by-step animation

示意:價格 7、2、10

回報動畫錯誤
步驟 1 / 3

排序

依價格遞減為 10、7、2。

10
7
2
年
1
成本
20

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
int main() {
    int t;
    cin >> t;
    const long long limit = 5000000;
    while (t--) {
        vector<long long> land;
        long long x;
        while (cin >> x && x)
            land.push_back(x);
        sort(land.begin(), land.end(), greater<long long>());
        long long total = 0;
        bool over = false;
        for (int i = 0; i < (int)land.size() && !over; ++i) {
            long long value = 2;
            for (int j = 0; j <= i; ++j) {
                if (value > limit / land[i]) {
                    over = true;
                    break;
                }
                value *= land[i];
            }
            if (!over) {
                total += value;
                over = total > limit;
            }
        }
        if (over)
            cout << "Too expensive\n";
        else
            cout << total << '\n';
    }
}

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

更多