首页 > 代码库 > 【POJ2891】Strange Way to Express Integers

【POJ2891】Strange Way to Express Integers

【题目大意】

给出k个模方程组:x mod ai = ri。求x的最小正值。如果不存在这样的x,那么输出-1.

【题解】

模板题,练习剩余定理的模板

 1 /*************
 2   POJ 2891
 3   by chty
 4   2016.11.3
 5 *************/
 6 #include<iostream>
 7 #include<cstdlib>
 8 #include<cstdio>
 9 #include<cstring>
10 #include<ctime>
11 #include<cmath>
12 #include<algorithm>
13 using namespace std;
14 #define MAXN 100000
15 typedef long long ll;
16 ll n,a[MAXN],m[MAXN];
17 inline ll read()
18 {
19     ll x=0,f=1;  char ch=getchar();
20     while(!isdigit(ch))  {if(ch==-)  f=-1;  ch=getchar();}
21     while(isdigit(ch))  {x=x*10+ch-0;  ch=getchar();}
22     return x*f;
23 }
24 ll exgcd(ll a,ll b,ll &x,ll &y)
25 {
26     if(!b)  {x=1; y=0; return a;}
27     ll r=exgcd(b,a%b,x,y);
28     ll t=x;x=y;y=t-a/b*y;
29     return r;
30 }
31 ll China()
32 {
33     ll A=a[1],M=m[1],k,y;
34     for(ll i=2;i<=n;i++)
35     {
36         ll g=exgcd(M,m[i],k,y),da=a[i]-A;
37         if(da%g)  return -1;
38         ll t=m[i]/g;
39         k*=da/g;
40         k=(k%t+t)%t;
41         A+=k*M;
42         M=M*m[i]/g;
43         A=(A+M)%M;
44     }
45     return A;
46 }
47 int main()
48 {
49     freopen("cin.in","r",stdin);
50     freopen("cout.out","w",stdout);
51     while(~scanf("%lld",&n))
52     {
53         for(ll i=1;i<=n;i++)  m[i]=read(),a[i]=read();
54         printf("%lld\n",China());
55     }
56     return 0;
57 }

 

【POJ2891】Strange Way to Express Integers