题目连接:
http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2644
题目类型:
数论 - 扩展欧几里得
数据结构:
无
思路分析:
将题目抽象成 公式:
( x + t * m ) % L = ( y + t * n ) % L
=> ( x + m * t ) - ( y + n * t ) = p * L
=> ( n - m ) * t + p * L = ( x - y )
设 n - m = A, x - y = B
求满足 A * t + p * L = B 的最小解
即求同余式 A * t = B ( mol L ) 的最小正整数解
具体过程:
1. ( n - m ) * t + p * L = ( x - y ) 的解 ( 利用扩展欧几里得 )
2. 若 ( x - y ) % gcd( n - m, L ) == 0, 则有解
3. 得到解后, 令 M = gcd( n - m, L ) , X = X * ( x - y ) / M;
4. ( X % ( L / M ) + L / M ) % ( L / M ) 即为最后解
证明:
暂无
源代码:
#include <iostream>
#include <stdio.h>
using namespace std;
__int64 _extend_gcd( __int64 a, __int64 b, __int64 * x, __int64 * y )
{
__int64 x0,x1,x2,y0,y1,y2;
__int64 r0,r1,r2,q;
if((a==0)&&(b==0)) { *x=0;*y=0; return -1; }
if((a==0)&&(b!=0)) { *x=0;*y=1; return b; }
if((a!=0)&&(b==0)) { *x=1;*y=0; return a; }
if((a!=0)&&(b!=0))
{
x0=0;x1=1;r0=a; y0=1;r1=b; r2=r0%r1; y1=0-r0/r1; x2=1;y2=y1;
if(r2==0) { x=0; *y=1; return r1; }
while((r1%r2)!=0)
{
r0=r1;r1=r2; q=r0/r1;
x2=x0-x1*q; y2=y0-y1*q;
x0=x1;x1=x2; y0=y1;y1=y2;
r2=r0%r1;
}
*x=x2; *y=y2;
return r2;
}
}
int main()
{
__int64 a, b;
__int64 x, y, m, n, L;
while( scanf( "%I64d%I64d%I64d%I64d%I64d", &x, &y, &m, &n, &L ) != EOF )
{
__int64 c = _extend_gcd( n - m, L, &a, &b );
if( ( x - y ) % c || m == n )
{
puts( "Impossible" );
}
else
{
__int64 s = L / c;
a = a * ( ( x - y ) / c );
a = ( a % s + s ) % s;
printf( "%I64d\n", a );
}
}
return 0;
}