結果

問題 No.186 中華風 (Easy)
ユーザー tsutajtsutaj
提出日時 2019-05-12 15:50:07
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,940 bytes
コンパイル時間 692 ms
コンパイル使用メモリ 77,860 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-27 00:55:37
合計ジャッジ時間 1,584 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 1 ms
4,380 KB
testcase_10 AC 2 ms
4,376 KB
testcase_11 AC 2 ms
4,376 KB
testcase_12 AC 2 ms
4,376 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 1 ms
4,376 KB
testcase_15 AC 1 ms
4,380 KB
testcase_16 AC 1 ms
4,376 KB
testcase_17 AC 1 ms
4,376 KB
testcase_18 AC 1 ms
4,380 KB
testcase_19 AC 2 ms
4,376 KB
testcase_20 AC 1 ms
4,376 KB
testcase_21 AC 1 ms
4,376 KB
testcase_22 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cassert>
#include <tuple>
using namespace std;

// 中国剰余定理
// x = b_1 (mod_1), ..., x = b_k (mod_k), ... を満たす x を
// 0 <= x < lcm(mod_1, mod_2, ..., mod_k, ...) の範囲で求める

template <typename NumType, NumType LIMIT = NumType(1e10)>
struct CRT {
    pair<NumType, NumType> NIL;
    CRT() : NIL(-1, -1) {}
    
    NumType extgcd(NumType a, NumType b, NumType &p, NumType &q) {
        if(b == 0) {
            p = 1, q = 0;
            return a;
        }
        NumType d = extgcd(b, a%b, q, p);
        q -= a / b * p;
        return d;
    }

    pair<NumType, NumType> solve(NumType b1, NumType mod1, NumType b2, NumType mod2) {
        NumType p, q;
        NumType d = extgcd(mod1, mod2, p, q);
        
        if((b2 - b1) % d != 0) return NIL;
        NumType s = (b2 - b1) / d;
        NumType t = (s * p % (mod2 / d));

        // get lcm
        NumType lc = mod1 / d * mod2;
        NumType so = (b1 + mod1 * t) % lc;
        (so += lc) %= lc;
        return make_pair(so, lc);
    }

    // m, mod の vector をもらって、
    // CRT の解を (x, lcm(mod_1, mod_2, ..., mod_k, ...)) の形で返す
    pair<NumType, NumType> solve(vector<NumType> m, vector<NumType> mod) {
        assert(m.size() == mod.size());
        NumType so = 0, lc = 1;
        for(size_t i=0; i<m.size(); i++) {
            tie(so, lc) = solve(so, lc, m[i], mod[i]);
            if(so > LIMIT or so < 0) {
                return NIL;
            }
        }
        return make_pair(so, lc);
    }
};


void yuki_186() {
    using ll = long long int;
    vector<ll> b(3), mod(3);
    for(int i=0; i<3; i++) {
        cin >> b[i] >> mod[i];
    }

    CRT<ll, (ll)2e18> crt;
    auto ans = crt.solve(b, mod);
    cout << ans.first + (ans.first == 0 ? ans.second : 0) << endl;
}

int main() {
    yuki_186();
    return 0;
}

0