Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m.
“It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?”
Since Elina is new to programming, this problem is too difficult for her. Can you help her?
Input
The input contains multiple test cases. Each test cases consists of some lines.
Line 1: Contains the integer k.
Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
Output
Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.
Sample Input
2
8 7
11 9
Sample Output
31
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
题意: 给你k对数(ai,ri),满足 m ≡ r (mod a) ,求出最小的m
很明显的线性同余方程组,因为ai之间不互斥,所以无法用CRT
而下面这个算法可以求解形如Ax≡Bx(mod M) 这样类型的线性同余方程组
并且mi之间不互斥时的情况
AC代码:
#include<iostream>
#include<cstdio>
using namespace std;
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define rev(i,s,e) for(int i=e;i>=s;i--)
#define all(x) x.begin(),x.end()
#define sz(x) x.size()
#define szz(x) int(x.size()-1)
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int MAXN = 1e5+10;
typedef long long LL;
typedef pair<LL,LL> PII;
LL a[MAXN],m[MAXN],b[MAXN];
void exgcd(LL a,LL b,LL &x,LL &y,LL &d)
{
if(!b) d = a,x=1,y=0;
else exgcd(b,a%b,y,x,d),y-=(a/b)*x;
}
LL inv(LL a,LL p)
{
LL x,y,d;
exgcd(a,p,x,y,d);
return d == 1?(x%p+p)%p:-1;
}
LL gcd(LL a,LL b)
{
if(!b) return a;
else return gcd(b,a%b);
}
PII liner(LL *A,LL *B,LL *M,int n) //求解Ax≡Bx(mod M) 这样类型的线性同余方程组
{
LL x = 0,m = 1;
rep(i,0,n-1)
{
LL a = A[i]*m,b = B[i]-A[i]*x,d = gcd(M[i],a);
if(b%d!=0) return PII(0,-1);
LL t = b/d*inv(a/d,M[i]/d)%(M[i]/d);
x = x+m*t;
m*=M[i]/d;
}
x = (x%m+m)%m;
return PII(x,m);
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif // LOCAL
// ios_base::sync_with_stdio(0);
// cin.tie(0),cout.tie(0);
int k;
while(~scanf("%d",&k))
{
rep(i,0,k-1)
{
a[i] = 1;
scanf("%I64d%I64d",&m[i],&b[i]);
}
PII ans = liner(a,b,m,k);
if(ans.second == -1) printf("-1\n");
else printf("%I64d\n",ans.first);
}
return 0;
}