zoukankan      html  css  js  c++  java
  • #C++初学记录(算法2)

    A - Game 23
    Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.

    Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.

    It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
    Input
    The only line of the input contains two integers n and m (1≤n≤m≤5⋅108).

    Output
    Print the number of moves to transform n to m, or -1 if there is no solution.

    Examples
    Input
    120 51840
    Output
    7
    Input
    42 42
    Output
    0
    Input
    48 72
    Output
    -1
    Note
    In the first example, the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840. The are 7 steps in total.

    In the second example, no moves are needed. Thus, the answer is 0.

    In the third example, it is impossible to transform 48 to 72.

    正确代码

    #include<cstdio>
    int res, num = 0,flag = 0, n, m;
    void getRes(int n, int m)
    {
        if(n == m)
        {
            res = num;
            flag = 1;
            return;
        }
        if(n > m)return;
        num++;
        getRes(n * 2, m);
        getRes(n * 3, m);
        num--;
    }
    int main()
    {
        scanf("%d %d", &n, &m);
        getRes(n, m);
        if(flag)
        {
            printf("%d
    ", res);
        }
        else
        {
            printf("-1
    ");
        }
        return 0;
    }
    

    代码理解
    解决这个问题首要想到的是使用递归函数进行运算,题目较为简单,但是实际解决时遇到问题导致不能AC,其一是因为受汉诺塔的影响使用递归时经常想要从后往前推,其实不然,递归问题由前往后推应该也是我们必须理解并使用的问题。这类题型就使用了递归问题由前向后推,由前向后推更容易理解,由后往前推也可以做出,使用变量num使之当做指示变量,进行几次递归则进行几次加一,递归使用后再进行相减得到原始变量防止运行程序出错。

  • 相关阅读:
    允许debian wheezy支持IOS7+的iphone.
    openSUSE 国内镜像摘要
    策略模式总结
    顺序串
    WindowState注意事项
    NLP | 自然语言处理
    Using Autorelease Pool Blocks
    NSAutoreleasePool & thread
    oc语言特性
    oc语言基础整理
  • 原文地址:https://www.cnblogs.com/xiaofengqaq/p/10706573.html
Copyright © 2011-2022 走看看