HDU 杭电5584 LCM Walk【逆推】

http://acm.hdu.edu.cn/showproblem.php?pid=5584

LCM Walk

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 518    Accepted Submission(s): 274


Problem Description
A frog has just learned some number theory, and can't wait to show his ability to his girlfriend.

Now the frog is sitting on a grid map of infinite rows and columns. Rows are numbered 1,2, from the bottom, so are the columns. At first the frog is sitting at grid (sx,sy) , and begins his journey.

To show his girlfriend his talents in math, he uses a special way of jump. If currently the frog is at the grid (x,y) , first of all, he will find the minimum z that can be divided by both x and y , and jump exactly z steps to the up, or to the right. So the next possible grid will be (x+z,y) , or (x,y+z) .

After a finite number of steps (perhaps zero), he finally finishes at grid (ex,ey) . However, he is too tired and he forgets the position of his starting grid!

It will be too stupid to check each grid one by one, so please tell the frog the number of possible starting grids that can reach (ex,ey) !
 

Input
First line contains an integer T , which indicates the number of test cases.

Every test case contains two integers ex and ey , which is the destination grid.

1T1000 .
1ex,ey109 .
 

Output
For every test case, you should output " Case #x: y", where x indicates the case number and counts from 1 and y is the number of possible starting grids.
 

Sample Input
   
   
   
   
3 6 10 6 8 2 8
 

Sample Output
   
   
   
   
Case #1: 1 Case #2: 2 Case #3: 3
 


我们暂时假设x,y的最大公约数gcd(x,y)=k,那么我们不妨用来表示x,用来表示y,那么新得到的点必定是,因为x与y的最小公倍数

我们不妨求解一下新的点x和y的gcd值,以点为例


因为时互质的,也是互质的,故


我们可以发现先得到的点和原来的点有相同的最大公约数,故我们可以利用这一点来根据终点求解原先的起点

还有一点需要知道的是,对于当前点(x,y),x,y中小的那个值必定是之前那个点中的x值或y值


AC代码


#include <cstdio>
int gcd(int a,int b){
	if(b==0) return a;
	return gcd(b,a%b);
}
void swap(int &a,int &b){
	int c=a;
	a=b;
	b=c;
}
int main(){
	int T;
	int a,b;
	int k=0;
	scanf("%d",&T);
	while(T--){
		scanf("%d%d",&a,&b);
		int c=gcd(a,b);
		int m1=a/c,m2=b/c;
		int ans=1;
		while(1){
			if(m1>m2) swap(m1,m2);
			if(m2%(m1+1)==0){
				m2/=(m1+1);
				ans++;
			}
			else break;
		}
		printf("Case #%d: %d\n",++k,ans);
	}
	return 0;
}


你可能感兴趣的:(HDU 杭电5584 LCM Walk【逆推】)