poj2891

来源:互联网 发布:淘宝 东京时光隧道 编辑:程序博客网 时间:2024/06/08 15:17

链接:点击打开链接

题意:解同余方程组

代码:

#include <math.h>#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;void exgcd(long long a,long long b,long long &d,long long &x,long long &y){    if(!b)    x=1,y=0,d=a;    else{    exgcd(b,a%b,d,y,x);    y-=x*(a/b);    }}int main(){    long long n,d,x,y,i,t,a,b,c,a1,a2,r1,r2,sign;    while(scanf("%I64d",&n)!=EOF){        sign=0;        scanf("%I64d%I64d",&a1,&r1);        for(i=1;i<n;i++){            scanf("%I64d%I64d",&a2,&r2);            a=a1,b=a2,c=r2-r1;            exgcd(a,b,d,x,y);                   //每两个同余方程组求出一组解,从而解出所有的解            if(c%d!=0)            sign=1;            t=b/d;            x=(x*(c/d)%t+t)%t;            r1=a1*x+r1;            a1=a1*(a2/d);        }        if(sign)        puts("-1");        else        printf("%I64d\n",r1);                   //解同余方程组的模板    }    return 0;}


 

0 0