b192中等

96 雲嘉區資訊學科能力競賽(2007)|英文句子數值加總

逐字計算連續英文字母個數,每個單字完成時產生min(9,字母數)的一位數。

解題思路

逐字計算連續英文字母個數,每個單字完成時產生min(9,字母數)的一位數。

逗號轉為小數點、句點只結束句子、空白只斷詞。由此得到兩個精確十進位字串。

將它們的小數位數對齊後以整數係數相加,再輸出去除不必要尾零的精確結果。

文字總長L,時間 O(L)解析加大整數加法,空間 O(L)。

Step-by-step animation

教學小例:單字長度編碼後精確十進位相加

回報動畫錯誤
步驟 1 / 3

句子A bb.與C ddd.

編碼為12與13

編碼為12與13
步驟
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);
}

string encode(string s) {
    string out;
    int len = 0;
    auto flush = [&]() {
        if (len) {
            out += char('0' + min(9, len));
            len = 0;
        }
    };
    for (char c : s) {
        if (isalpha((unsigned char)c))
            len++;
        else {
            flush();
            if (c == ',')
                out += '.';
        }
    }
    flush();
    return out;
}

int main() {
    string a, b;
    getline(cin, a);
    getline(cin, b);
    cout << (Dec(encode(a)) + Dec(encode(b))).str() << '\n';
}

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

更多