HDU 5584 LCM Walk 数学

    xiaoxiao2025-09-13  844

    LCM Walk

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

    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.

    ⋅ 1≤T≤1000. ⋅ 1≤ex,ey≤109.

    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

    Source 2015ACM/ICPC亚洲区上海站-重现赛(感谢华东理工)

    Recommend wange2014

    如果y>x,则一定是之前的点通过变化y',x不变才得到(x,y),x>y则反过来。 设当前点为(x,y),且y>x,则前一个点存在的话就一定是(x,y-z),其中z=LCM(x,y-z),不可能是x变小。 公式:gcd(x,y)=gcd(x,y-k*x) 由题意及题设得:x*(y-z)=z*gcd(x,y-z) (因为两个数的乘积等于两个数的gcd和lcm的乘积) 又z=LCM(x,y-z),故z是x的整数倍,即z=k*x 所以gcd(x,y-z)=gcd(x,y-k*x)=gcd(x,y) 设g=gcd(x,y),则x*(y-z)=z*g 化简可得:z=(x*y)/(g+x) (一定要是整除才行,如果(x*y)%(g+x)不等于0则退出) 同时保证z>=x && z<y 且z则是x和(y-z)的倍数。 当x==y时则前面就不可能再有点了,注意就是一直保证y>x。 #include<stdio.h> #include<string> #include<cstring> #include<queue> #include<algorithm> #include<functional> #include<vector> #include<iomanip> #include<math.h> #include<iostream> #include<sstream> #include<stack> #include<set> #include<bitset> using namespace std; typedef long long LL; int main() { LL x,y,T,res,kcase=1; scanf("%I64d",&T); while(T--) { scanf("%I64d%I64d",&x,&y); res=1; while(x!=y) { LL g=__gcd(x,y); if(x>y) { LL t=x; x=y; y=t; } if((x*y)%(x+g)) break; LL z=(x*y)/(g+x); if(z%x || z<x || z>=y || z%(y-z)) break; y-=z; res++; } printf("Case #%I64d: %I64d\n",kcase++,res); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1302616.html
    最新回复(0)