poj2891 Strange Way to Express Integers 同余方程组

来源:互联网 发布:net mysql 编辑:程序博客网 时间:2024/05/29 06:54

题意:给你k对整数(ai,ri),已知对于每对整数,m%ai=ri,问你求m的最小值,不存在输出-1

即解同余方程组m≡ri(mod ai) 合并方程即可

#include<cstdio>#include<iostream>#include<algorithm>typedef long long int ll;using namespace std;ll x,y;ll Extended(ll a,ll b){  if(b==0){    x=1;y=0;    return a;  }  ll d=Extended(b,a%b);  ll temp=x;  x=y;  y=temp-a/b*y;  return d;}ll gcd(ll a,ll b){if(b==0)    return a;return gcd(b,a%b);}int main(){   int k;  while(cin>>k){   ll b1,b2,m1,m2;   cin>>m1>>b1;   bool f=1;   for(int i=1;i<k;i++){    cin>>m2>>b2;    if(f==1){    ll m=gcd(m1,m2);    if(((b2-b1)%m)!=0)        f=0;    else  {          ll d=(b2-b1)/m;          Extended(m1,m2);          ll t=m2/m;          ll c=((x%t)*(d%t)%t+t)%t;          b1=b1+c*m1;          m1=m1*m2/m;    }   }  }  if(f==1){    cout<<b1<<endl;  }  else cout<<-1<<endl;   }}



阅读全文
0 0
原创粉丝点击