[POJ] [1061] Frog's Date

Problem Description

Loading...

Problem Analysis

It is easy to think of the extended Euclidean algorithm.
From the problem statement we get

$$\begin{align*} & \left( x+m\cdot t\right) -\left( y+n\cdot t\right) =k\cdot L\\ & \Rightarrow \\ & \left( m-n\right) t-k\cdot L=y-x\end{align*}$$

Convert it into $a\cdot x+b\cdot y=gcd\left( a,b\right)$
Then

$$\begin{cases} a=m-n \\ b=-L\\ x=t \\ y=k \end{cases}$$

Therefore we can determine whether gcd(m-n,-L) divides (y-x)
Since L must be greater than 0
So write the equation as $\left( n-m\right) t+k\cdot L=x-y$
Use the extended Euclidean algorithm to find x and y
The rest can be used to find t
Then consider the case t<0
Quote a solution:

Theorem 1: If d =gcd(a, b), then there must exist integers k and l, positive or negative, such that d = ax+ by.
Theorem 2: If gcd(a,b) = 1, then the equation ax ≡ c (mod b) has a unique solution in [0, b-1].
Theorem 3: If gcd(a,b) = d, then the equation ax ≡ c (mod b) has a unique solution in [0, b/d - 1].
Proof: The above congruence equation is equivalent to ax + by = c. If it has a solution, dividing both sides by d gives a/d * x + b/d * y = c/d, i.e. a/d * x ≡ c/d (modb/d). Clearly gcd(a/d, b/d) = 1, so by Theorem 2 we know x has a unique solution in [0, b/d - 1]. Therefore the x in ax + by = c has a unique solution in [0, b/d - 1], i.e. ax ≡ c (mod b) has a unique solution in [0, b/d - 1].
If a particular solution X of ax ≡ c (mod b) is obtained, then let r = b/gcd(a, b). We know x has a unique solution in [0, r-1], so x = (x% r + r) % r gives the smallest non-negative integer solution x! (X % r may be negative; in that case it stays within [-(r-1), 0], while a positive value stays within [0, r-1]. Adding r keeps it within [1, 2r - 1], so taking the modulus by r again puts it within [0, r-1]).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
long long exgcd(long long a,long long b,long long &x,long long &y) {
	if(b==0) {
		x=1,y=0;
		return a;
	}
	long long d=exgcd(b,a%b,y,x);
	y-=x*(a/b);
	return d;
}
int main() {
	long long x,y,m,n,L;
	while(scanf("%lld %lld %lld %lld %lld",&x,&y,&m,&n,&L)!=EOF) {
		long long t1,t2;
		long long d=exgcd(n-m,L,t1,t2);
		if((y-x)%d!=0)
			printf("Impossible\n");
		else {
			t1=t1*((x-y)/d);
			long long r=L/d;
			t1=(t1%r+r)%r;
			printf("%lld\n",t1);
		}
	}
	return 0;
}

Recommended article: POJ 1061 Frog’s Date - w446506278’s Blog

Loading...