noi2018d2t1

题解:

ex-crt

学习见https://www.cnblogs.com/Miracevin/p/9254795.html

hdu2891

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
#define rint register int
#define IL inline
#define rep(i,h,t) for (int i=h;i<=t;i++)
#define dep(i,t,h) for (int i=t;i>=h;i--)
#define ll long long
const int N=2e5;
int n;
ll r[N],a[N];
ll gcd(ll a,ll b,ll &x,ll &y)
{
  if (b==0)
  {
    x=1; y=0; return(a);
  }
  ll ans=gcd(b,a%b,y,x);
  y-=x*(a/b);
  return ans;
}
ll solve()
{
  ll R=r[1],A=a[1],x,y,d;
  rep(i,2,n)
  {
    d=gcd(A,a[i],x,y);
    if ((R-r[i])%d!=0) return(-1);
    x=(R-r[i])/d*x%a[i];
    R-=x*A;
    A=A/d*a[i];
    R%=A;
  }
  return (R%A+A)%A; 
}
int main()
{
  freopen("1.in","r",stdin);
  freopen("1.out","w",stdout);
  ios::sync_with_stdio(false);
  while (cin>>n)
  {
    rep(i,1,n) cin>>a[i]>>r[i];
    cout<<solve()<<endl;
  }
  return 0;
}

 

posted @ 2018-07-21 10:54  尹吴潇  阅读(150)  评论(0编辑  收藏  举报