結果

問題 No.186 中華風 (Easy)
ユーザー 303Yuyu303Yuyu
提出日時 2021-02-25 23:41:12
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,947 bytes
コンパイル時間 2,051 ms
コンパイル使用メモリ 166,732 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-09 02:56:00
合計ジャッジ時間 2,916 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

using ll = long long;

// 負の数にも対応したmod
inline ll mod(ll a, ll m) {
    return (a % m + m) % m;
}

// 拡張ユークリッドの互除法
// ax + by = gcd(a, b)を満たす(x, y)を計算。gcd(a, b)を返す
ll ext_gcd(ll a, ll b, ll& x, ll& y) {
    if(b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = ext_gcd(b, a%b, y, x);
    y -= a/b * x;
    return d;
}

// ax=1(mod m)となるxを返す。解なしだと-1を返す
ll mod_inv(ll a, ll m) {
    ll x, y, d;
    d = ext_gcd(a, m, x, y);
    if(d == 1) return mod(x, m);
    else return -1;
}

// 中国剰余定理
// x=B (mod M)となる(r, m)を返す
// 解なしの場合は(0, -1)を返す
pair<ll, ll> chinese_rem(const vector<ll>& B, const vector<ll>& M) {
    ll x = 0, m = 1;
    for(int i = 0; i < (int)B.size(); ++i) {
        ll p, q;
        ll d = ext_gcd(m, M[i], p, q);  //pは M/d (mod m[i]/d) の逆元
        if((B[i] - x) % d != 0) return {0, -1};
        ll t = (B[i] - x) / d * p % (M[i] / d);
        x += m * t;
        m *= M[i] / d;
    }
    return {mod(x, m), m};
}
// Ax=B (mod M)を解く
pair<ll, ll> linear_congruence(const vector<ll>& A, const vector<ll>& B, const vector<ll>& M) {
    ll x = 0, m = 1;
    for(int i = 0; i < (int)A.size(); ++i) {
        ll a = A[i] * m;
        ll b = B[i] - A[i] * x;
        ll d = __gcd(M[i], a);
        if(b % d != 0) return {0, -1};
        ll t = b / d * mod_inv(a / d, M[i] / d) % (M[i] / d);
        x = x + m * t;
        m *= M[i] / d;
    }
    return {mod(x, m), m};
}

// https://yukicoder.me/problems/447
int main() {
    vector<ll> B(3), M(3);
    for(int i = 0; i < 3; ++i) cin >> B[i] >> M[i];

    pair<ll, ll> p = chinese_rem(B, M);
    if(p.second == -1) {    // 解なし
        cout << -1 << endl;
        return 0;
    }
    ll ans = p.first;
    if(ans == 0) ans += p.second;
    cout << ans << endl;
}
0