Hdoj.5584 LCM Walk【数论,规律】 2015/12/04

来源:互联网 发布:杭州淘宝村在哪里 编辑:程序博客网 时间:2024/05/16 14:58

LCM Walk

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


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 numbered1,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", wherex indicates the case number and counts from 1 and y is the number of possible starting grids.
 

Sample Input
36 106 82 8
 

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

Source
2015ACM/ICPC亚洲区上海站-重现赛(感谢华东理工)  
题意:从(x,y)点出发,可以向上或向右走,每次走的距离为LCM(x,y),即移动后的坐标为(x+LCM(x,y),y)或(x,y+LCM(x,y)),移动若干次后停止在(ex,ey)点,问有多少点可以移动到点(ex,ey)。

解析:假设从(x,y)点出发,设x,y的最大公约数为k,则x=mk,y=nk,LCM(x,y) = (x*y)/gcd(x,y)=(mk*nk)/k=mnk,移动后的坐标:向右移(x,y+LCM(x,y)) = (mk,n(1+m)k),向上移(x+LCM(x,y),y) = (m(1+n)k,nk),由于m与n互质,且m与m+1,n与n+1也互质,即移动后的坐标的最大公约数也为k,由此,可以从终点坐标倒着走
#include<iostream>#include<cstdio>#include<cstring>using namespace std;int gcd(int a,int b){    return b?gcd(b,a%b):a;}int main(){    int t,ans=1,x,y;    cin>>t;    while(t--){        cin>>x>>y;        printf("Case #%d: ",ans++);        int num=1;        int res = gcd(x,y);        while( 1 ){            if( x < y ){                int m1 = x / res;                int m2 = y / res;                if( m2%(1+m1) == 0 )                    num++;                else break;                y = m2/(1+m1)*res;            }            else{                int m2 = y / res;                int m1 = x / res;                if( m1%(m2+1) == 0 )                    num++;                else break;                x = m1/(1+m2)*res;            }        }        printf("%d\n",num);    }    return 0;}


0 0
原创粉丝点击