204. 表达整数的奇怪方式(exgcd,,,数学推导,借助中国剩余定理)

204. 表达整数的奇怪方式

题意:

在这里插入图片描述

y总的笔记

在这里插入图片描述

墨染空大佬的 题解%%%%%

AC

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll exgcd(ll a, ll b, ll& x, ll& y){
    
    
    if(b==0){
    
    
        x = 1, y= 0;
        return a;
    }
    ll d = exgcd(b,a%b,y,x);
    y -= a/b*x;
    return d;
}
int main(){
    
    
    ios::sync_with_stdio(0);
    int n;
    cin>>n;
    
    ll a1, m1;
    cin>>a1>>m1;
    bool ok = true;
    //ll res = 0;
    for(int i = 1; i < n; i ++ ){
    
    
        ll a2, m2;
        cin>>a2>>m2;
        
        ll k1, k2;
        ll d = exgcd(a1,a2,k1,k2);
        if((m2-m1)%d){
    
    
            ok = false;
            break;
        }
        k1 *= (m2-m1)/d;
        ll mod = (a2/d);
        k1 = (k1%mod+mod)%mod;
        
        m1 = a1*k1+m1;
        a1 = a1/d*a2;
    }
    if(!ok)puts("-1");
    else cout<<(m1%a1+a1)%a1;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45377553/article/details/113488116