b248中等

108 彰雲嘉區資訊學科能力競賽(2019)|計算服務需要的時間

令finish[j]為目前已處理顧客在第j步的完成時間。

解題思路

令finish[j]為目前已處理顧客在第j步的完成時間。

對下一位顧客,第j步開始前必須同時等自己前一步與前一人此櫃檯完成,所以finish[j]=max(finish[j],finish[j-1])+time。j=0前一步視為0。

從左往右更新時,finish[j]舊值與finish[j-1]新值剛好是兩個依賴。用任意精度十進位係數避免浮點誤差,最後輸出最後櫃檯完成時間。

時間 O(NK)次精確十進位比較加法;空間 O(K)個數值,Python逐行讀取另需 O(K)輸入字串,每數位數成本另計。

Step-by-step animation

教學小例:流水線完成時間與精確十進位

回報動畫錯誤
步驟 1 / 3

兩顧客兩步

(1,3)、(2,1)

(1,3)、(2,1)
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
cpp_int ten(int k) {
    cpp_int x = 1;
    while (k--)
        x *= 10;
    return x;
}

struct Dec {
    cpp_int n;
    int s;
    Dec(cpp_int a = 0, int b = 0) : n(a), s(b) {
    }
    Dec(string x) {
        s = 0;
        n = 0;
        bool neg = false, point = false;
        for (char c : x) {
            if (c == '-')
                neg = true;
            else if (c == '.')
                point = true;
            else if (isdigit(c)) {
                n = n * 10 + c - '0';
                s += point;
            }
        }
        if (neg)
            n = -n;
    }
    string str() const {
        cpp_int q = n;
        bool neg = q < 0;
        if (neg)
            q = -q;
        string x = q.convert_to<string>();
        if (s) {
            if ((int)x.size() <= s)
                x = string(s + 1 - x.size(), '0') + x;
            x.insert(x.size() - s, 1, '.');
            while (x.back() == '0')
                x.pop_back();
            if (x.back() == '.')
                x.pop_back();
        }
        if (neg && q != 0)
            x = "-" + x;
        return x;
    }
};

Dec operator+(Dec a, Dec b) {
    int s = max(a.s, b.s);
    return Dec(a.n * ten(s - a.s) + b.n * ten(s - b.s), s);
}

Dec operator-(Dec a, Dec b) {
    b.n = -b.n;
    return a + b;
}

Dec operator*(Dec a, Dec b) {
    return Dec(a.n * b.n, a.s + b.s);
}

bool operator<(Dec a, Dec b) {
    int s = max(a.s, b.s);
    return a.n * ten(s - a.s) < b.n * ten(s - b.s);
}

int main() {
    int n, k;
    cin >> n >> k;
    vector<Dec> d(k);
    string s;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < k; j++) {
            cin >> s;
            Dec before = j ? d[j - 1] : Dec();
            if (d[j] < before)
                d[j] = before;
            d[j] = d[j] + Dec(s);
        }
    cout << d.back().str() << '\n';
}

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

更多