POJ 2891 Strange Way to Express Integers
求N个同余方程,用扩展欧几里得。
扩展欧几里得算法是用来在已知a,b的情况下求解一组x,y 使得 ax+by = gcd(a,b)
原理:
gcd(a,b) = gcd(b, a%b)
=> ax+by = gcd(a,b) = gcd(b, a%b);
=>ax+by=bx+(a%b)y;
=>ax+by=bx1+(a-(a/b)*b)y1=ay1+bx1-(a/b)*by1;
=>x=y1;y=x1-(a/b)*y1;
#include"iostream" using namespace std; __int64 egcd(__int64 a,__int64 b,__int64 &x,__int64 &y)//扩展欧几里得 { __int64 tmp,i; if(b==0) { x=1;y=0; return a;//返回gcd(m1,m2) } i=egcd(b,a%b,x,y); tmp=x;x=y;y=tmp-a/b*y; return i;//返回gcd(m1,m2) } int main() { int n; while(cin>>n) { __int64 m1,r1,m2,r2,a,b,x,y; int flag=1,i,j; cin>>m1>>r1; for(i=1;i<n;i++) { cin>>m2>>r2; if(!flag) continue; a=egcd(m1,m2,x,y); if((r2-r1)%a!=0) { flag=0; continue; } x=x*(r2-r1)/a; b=m2/a; x=(x%b+b)%b; r1=r1+m1*x; m1=(m1*m2)/a; } if(flag) cout<<r1<<endl; else cout<<-1<<endl; } return 0; }