HDU 5584 LCM Walk【搜索】

题目链接:

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

题意:

分析:

这题比赛的时候卡了很久,一直在用数论的方法解决。
其实从终点往前推就可以发现,整个过程中的点的gcd都是一样的,利用这个性质倒着搜索一遍就好了。
相同的gcd均为
整除就可以了。

代码:

#include<iostream>
using namespace std;
int gcd(int a, int b){ return b?gcd(b, a % b):a;}
int cnt = 0;
int g;
int c = 1;
void dfs(int a, int b)
{
    if(a < 1 || b < 1) return ;
    cnt++;
    if(a % (b + 1) == 0) dfs(a / (b + 1), b);
    if(b % (a + 1) == 0) dfs(a,  b/(a + 1));
}
int main (void)
{
    int T;cin>>T;
    while(T--){
        int x, y;
        cin>>x>>y;
        g = gcd(x, y);
        x /= g;
        y /= g;
        cnt = 0;
        dfs(x, y);
        cout<<"Case #"<<c<<": "<<cnt<<endl;
        c++;
    }
    return 0;
}