x % a1 = m1
x % a2 = m2
...
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
typedef long double ld;
ll exgcd(ll a, ll b, ll &x, ll &y)
{
if(!b)
{
x = 1, y = 0;
return a;
}
ll d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main()
{
IOS
int n;
cin >> n;
ll a1, m1, a2, m2;
cin >> a1 >> m1;
int f = 1;
for(int i = 1; i < n; i ++)
{
cin >> a2 >> m2;
ll k1, k2;
ll d = exgcd(a1, a2, k1, k2);
if((m2 - m1) % d)
{
f = 0;
break;
}
k1 *= (m2 - m1) / d;
ll t = a2 / d;
k1 = (k1 % t + t) % t;
m1 = a1 * k1 + m1;
a1 = abs(a1 * t);//不取绝对值也可以
}
if(f)cout << (m1 % a1 + a1) % a1;//弄成正数
else cout << -1;
return 0;
}
其实m1就是答案,最后没必要(m1 % a1 + a1) % a1
如果还要再判断有无答案超过上限m的情况,可以在每次计算完m1后判断是否>m..但注意:即使判断完后也不要break掉,因为后面同样有可能判断到无解情况。
总之就默认答案一定在int128范围内吧
D-Han Xin and His Troops_2024牛客五一集训派对day1 (nowcoder.com)
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
typedef long double ld;
ll n, m;
void scan(__int128 &x)//输入
{
x = 0;
int f = 1;
char ch;
if((ch = getchar()) == '-') f = -f;
else x = x*10 + ch-'0';
while((ch = getchar()) >= '0' && ch <= '9')
x = x*10 + ch-'0';
x *= f;
}
void print(__int128 x)
{
if(x < 0)
{
x = -x;
putchar('-');
}
if(x > 9) print(x/10);
putchar(x%10 + '0');
}
__int128 exgcd(__int128 a, __int128 b, __int128 &x, __int128 &y)
{
if(!b)
{
x = 1, y = 0;
return a;
}
__int128 d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main()
{
//scan(n);
//scan(m);
scanf("%lld%lld", &n, &m);
getchar();//要getchar吸收一个空格或者回车 因为快读会自己吸收后面一个空格或者回车
__int128 a1, m1, a2, m2;
scan(a1); scan(m1);
int f = 1, ff = 0;
for(int i = 1; i < n; i ++)
{
scan(a2); scan(m2);
__int128 k1, k2;
__int128 d = exgcd(a1, a2, k1, k2);
if((m2 - m1) % d)
{
f = 0;
break;
}
k1 *= (m2 - m1) / d;
__int128 t = a2 / d;
k1 = (k1 % t + t) % t;
m1 = a1 * k1 + m1;
a1 *= t;
}
if(f == 0) cout << "he was definitely lying";
else if(m1 > (__int128)m) cout << "he was probably lying";
else cout << (ll)m1;
return 0;
}