b165中等

90 台中區資訊學科能力競賽(2001)|分段用電費用

將用電量按300、300、400及其餘四段分割,分別乘9、8、6、5。

解題思路

將用電量按300、300、400及其餘四段分割,分別乘9、8、6、5。

每段只取尚未計費的用電量與段長的最小值,所以各單位恰被計一次。

保存十進位整數係數及小數位數,對齊位數後加減,避免浮點誤差;最後再累計人數、用電與費用。

每筆固定次數十進位運算;位數D時各次加減乘小整數 O(D),總空間隨數字位數及輸出大小。

Step-by-step animation

教學小例:累進分段與精確十進位

回報動畫錯誤
步驟 1 / 3

用電300.5

首300單位乘9得2700

首300單位乘9得2700
步驟
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() {
    string id, s;
    Dec total, fee;
    long long count = 0;
    while (cin >> id >> s) {
        Dec x(s), left = x, cost;
        int lens[] = {300, 300, 400};
        int rates[] = {9, 8, 6};
        for (int i = 0; i < 3; i++) {
            Dec use = left < Dec(lens[i]) ? left : Dec(lens[i]);
            cost = cost + use * Dec(rates[i]);
            left = left - use;
        }
        cost = cost + left * Dec(5);
        total = total + x;
        fee = fee + cost;
        count++;
        cout << id << ' ' << x.str() << ' ' << cost.str() << '\n';
    }
    cout << count << ' ' << total.str() << ' ' << fee.str() << '\n';
}

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

更多