b168中等

108 台中區資訊學科能力競賽(2019)|普通分數之四則運算

逐個讀取正整數分子、/、正整數分母,將它們視為一個完整分數項;下一個符號才是項間運算子。

解題思路

逐個讀取正整數分子、/、正整數分母,將它們視為一個完整分數項;下一個符號才是項間運算子。

維持已完成的加減總和與目前乘除項,遇乘除直接更新目前項;遇加減則先結算前項。

每次分數運算用最大公因數約分,分母維持正值。缺少數字、0分子或分母、非法符號及數字間空白拼接均判錯。

共L字元及T分數項,解析 O(L),運算為 O(T)次任意精度有理數運算;實際成本取決於中間分子分母位數。

Step-by-step animation

教學小例:分數詞法分析與兩層運算優先序

回報動畫錯誤
步驟 1 / 3

1/2+1/3*3/1

先讀1/2為目前項

先讀1/2為目前項
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
cpp_int gcdBig(cpp_int a, cpp_int b) {
    if (a < 0)
        a = -a;
    if (b < 0)
        b = -b;
    while (b != 0) {
        cpp_int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

struct Rat {
    cpp_int p, q;
    Rat(cpp_int a = 0, cpp_int b = 1) : p(a), q(b) {
        if (q < 0)
            p = -p, q = -q;
        cpp_int g = gcdBig(p, q);
        p /= g;
        q /= g;
    }
};

Rat operator+(Rat a, Rat b) {
    return Rat(a.p * b.q + b.p * a.q, a.q * b.q);
}
Rat operator-(Rat a, Rat b) {
    return Rat(a.p * b.q - b.p * a.q, a.q * b.q);
}
Rat operator*(Rat a, Rat b) {
    return Rat(a.p * b.p, a.q * b.q);
}
Rat operator/(Rat a, Rat b) {
    return Rat(a.p * b.q, a.q * b.p);
}

int main() {
    string s;
    while (getline(cin, s)) {
        size_t i = 0;
        bool ok = true;
        auto skip = [&]() {
            while (i < s.size() && isspace((unsigned char)s[i]))
                i++;
        };
        auto num = [&]() {
            skip();
            cpp_int n = 0;
            size_t st = i;
            while (i < s.size() && isdigit((unsigned char)s[i]))
                n = n * 10 + s[i++] - '0';
            if (i == st || n == 0)
                ok = false;
            return n;
        };
        auto frac = [&]() {
            cpp_int a = num();
            skip();
            if (i >= s.size() || s[i++] != '/')
                ok = false;
            cpp_int b = num();
            if (b == 0)
                b = 1;
            return Rat(a, b);
        };
        Rat sum, term = frac();
        int sign = 1;
        while (ok) {
            skip();
            if (i == s.size())
                break;
            char op = s[i++];
            if (string("+-*/").find(op) == string::npos) {
                ok = false;
                break;
            }
            Rat v = frac();
            if (op == '*')
                term = term * v;
            else if (op == '/')
                term = term / v;
            else {
                sum = sign == 1 ? sum + term : sum - term;
                term = v;
                sign = op == '+' ? 1 : -1;
            }
        }
        if (!ok)
            cout << -1 << '\n';
        else {
            sum = sign == 1 ? sum + term : sum - term;
            cout << sum.p << '/' << sum.q << '\n';
        }
    }
}

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

更多