萌新 excrt 求调,玄关
  • 板块灌水区
  • 楼主Tomwsc
  • 当前回复8
  • 已保存回复8
  • 发布时间2025/1/4 17:38
  • 上次更新2025/1/4 21:41:52
查看原帖
萌新 excrt 求调,玄关
1418967
Tomwsc楼主2025/1/4 17:38

代码如下:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 1e5 + 10;
int n;
int a[MAXN] , b[MAXN];
  
int gcd(int a , int b) {
    if(!b)
        return a;
    return gcd(b , a % b);
}
  
inline int lcm(int a , int b) {
    int r = gcd(a , b);
    return a / r * b / r;
}
  
int exgcd(int a , int b , int &x , int &y) {
    if(!b) {
        x = 1;
        y = 0;
        return a;
    }
    int r = exgcd(b , a % b , x , y);
    int t = x;
    x = y;
    y = t - a / b * y;
    return r;
}
  
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    while(cin >> n) {
        bool flag = false;
        for(register int i = 1;i <= n;i ++)
            cin >> b[i] >> a[i];
        int a1 = a[1] , b1 = b[1];
        int x , y;
        int ans;
        for(register int i = 2;i <= n;i ++) {
            int a2 = a[i] , b2 = b[i] , c2 = a2 - a1;
//          cout << "x = " << a1 << " (mod " << b1 << ")" << '\n';
//          cout << "x = " << a2 << " (mod " << b2 << ")" << '\n';
//          cout << b1 << "x + " << b2 << "y = " << a2 - a1 << '\n' << '\n';
            int r = exgcd(b1 , b2 , x , y);
            if(c2 % r != 0) {
                flag = true;
                break;
            }
            int p = b2 / r;
            x = x * c2 / r;
            x = (x % p + p) % p;
//            int mod = b1;
            ans = a1 + b1 * x;
            b1 = lcm(b1 , b2);
            a1 = ans % b1;
        }
        if(flag) {
            cout << -1 << '\n';
            continue;
        }
        cout << ans << '\n';
    }
    return 0;
}
/*
x = a1 (mod b1)
x = a2 (mod b2)
x = a1 + b1 * k1 = a2 + b2 * k2
b1 * k1 + b2 * k2 = a2 - a1
*/
2025/1/4 17:38
加载中...