a190簡單數論、質數與因數

TOI 2020/05 新手組:韓信點兵

逐條合併餘數條件,用已滿足模數的乘積跳步。

前往題目練習 →回報教學錯誤時間 O(a₁+a₂+a₃),空間 O(1)。

這題在學什麼

先令 x=0、step=1;處理一條 x mod a=b 時,反覆將 x 加 step,直到符合。

因 step 是先前模數的乘積,加 step 不會破壞已滿足的餘數條件;兩兩互質保證最多試 a 次。

合併後把 step 乘 a;最後 x 是一週期內最小非負解,若為 0 就改輸出 step 作為最小正解。

Step-by-step animation

韓信點兵・遞增合併同餘

回報動畫錯誤
步驟 1 / 3

第一條餘數

從 0 每次加 1,最先得到 3 mod 5=3。

x=3
step=5
已滿足
mod 5 = 3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    long long x = 0, step = 1;
    for (int i = 0; i < 3; i++) {
        long long a, b;
        cin >> a >> b;
        while (x % a != b)
            x += step;
        step *= a;
    }
    cout << (x ? x : step) << '\n';
}

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

更多