算法设计与分析: 5-8 整数变换问题

5-8 整数变换问题


问题描述

整数变换问题。关于整数 i 的变换 f 和 g 定义如下: f ( i ) = 3 i ; g ( i ) = i / 2
试设计一个算法,对于给定的 2 个整数 n 和 m,用最少的 f 和 g 变换次数将 n 变换为 m。
例如,可以将整数 15 用 4 次变换将它变换为整数 4: 4=gfgg(15)。当整数 n 不可能变换为整数 m 时,算法应如何处理?

对任意给定的整数 n 和 m,编程计算将整数 n 变换为整数 m 所需要的最少变换次数。

数据输入:
第一行有 2 个正整数 n 和 m。


Java

package Chapter5HuiSuFa;

import java.util.Scanner;

public class ZhengShuBianHuan {

    private static int n,m,k;
    private static boolean found;
    private static int maxdep;
    private static int MAX = 10000;
    private static int[] t,bestx;

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        while(true){
            maxdep = MAX;
            n = input.nextInt();
            m = input.nextInt();

            t = new int[MAX];
            bestx = new int[MAX];

            compute();
        }
    }

    private static void compute(){
        k = 1;
        while (!search(1,n)){
            k++;
            if(k > maxdep) break;
//            init();
            t = new int[MAX];
            bestx = new int[MAX];
        }
        if(found) {
//            output();
            System.out.println(k);
            for(int i=k; i>=1; i--)
                if(bestx[i] == 1)
                    System.out.print('f');
                else
                    System.out.print('g');
        }
        else
            System.out.println("No Solution!");
    }

    private static boolean search(int dep, int n){
        if(dep > k) return false;
        for(int i=0; i<2; i++){
            int n1 = f(n,i);
            t[dep] = i;
            if(n1==m ||search(dep+1,n1)){
                found = true;
//                out();
                for(int j=1; j<=k; j++)
                    bestx[j] = t[j];
                return true;
            }
        }

        return false;
    }

    private static int f(int n, int i){
        if(i == 1)
            return 3*n;
        else
            return n/2;
    }
}

Input & Output

15 4
4
gfgg

82 54
8
fffggggg

Reference

王晓东《计算机算法设计与分析》(第3版)P182

猜你喜欢

转载自blog.csdn.net/ioio_/article/details/81104838
5-8