結果

問題 No.186 中華風 (Easy)
ユーザー simkarensimkaren
提出日時 2019-09-18 11:24:57
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,744 bytes
コンパイル時間 1,519 ms
コンパイル使用メモリ 170,768 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-27 00:56:49
合計ジャッジ時間 2,472 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,380 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 2 ms
4,376 KB
testcase_16 AC 1 ms
4,380 KB
testcase_17 AC 1 ms
4,376 KB
testcase_18 AC 1 ms
4,380 KB
testcase_19 AC 1 ms
4,380 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 <bits/stdc++.h>

using namespace std;

#define ll long long

/* aとbの最大公約数を求める. */
ll gcd(ll a, ll b){
    if (b > a) return gcd(b, a);
    if (b == 0) return a;
    return gcd(b, a % b);
}

/* ax+by=gcd(a,b)を満たす(x,y)を格納し、gcd(a,b)を返す. */
ll extgcd(ll a, ll b, ll& x, ll& y){
    if (b > a) return extgcd(b, a, y, x);
    if (b == 0){
        x = 1; y = 0;
        return a;
    }
    int g = extgcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
}

/* mod mでのaの逆元を求める.(gcd(a,m) = 1) */
ll modinv(ll a, ll m){
    ll x, y;
    extgcd(a, m, x, y);
    return (m + x % m) % m;
}

/* 連立線形方程式を解く.
        A[i] * x ≡ B[i] (mod M[i])
    なる方程式の解が
        x ≡ b (mod m)
    とかけるとき、(b, m)を返す.(存在しなければ(0, -1)) */
pair<ll, ll> liner_congruence(
    vector<ll> A, vector<ll> B, vector<ll> M
){
    ll x = 0, m = 1;

    for (int i = 0; i < A.size(); ++i){
        ll a = A[i] * m,
         b = B[i] - A[i] * x,
         d = gcd(M[i], a);

        if (b % d != 0) // 解なし
            return make_pair(0, -1);
        
        ll t = b / d * modinv(a / d, M[i] / d) % (M[i] / d);
        x = x + m * t;
        m *= M[i] / d;
    }

    return make_pair(x % m, m);
}

signed main(){
    vector<ll> a(3);
    a[0] = a[1] = a[2] = 1;
    vector<ll> b(3), m(3);
    for (int i = 0; i < 3; ++i){
        ll x, y; cin >> x >> y;
        b[i] = x; m[i] = y;
    }
    
    auto ans = liner_congruence(a, b, m);
    if (ans.second == -1)
        cout << -1 << endl;
    else if (ans.first > 0)
        cout << ans.first << endl;
    else
        cout << (ans.first + ans.second) << endl;
    
    return 0;
}
0