整数变换问题-回溯法
算法思想:回溯法
depth=1 时
第一层 n 返回false
depth=2 时
第一层 n
第二层 n*3 n/2 不满足 返回 false;
depth=3 时
第一层 n
第二层 n3 n/2
第三层 n33 n3/2 n/2*3 n/2/2 不满足 返回 false;
当depth=4时候,满足,返回true,则进行回溯,回到上一层,最后到根
方式1:键盘输入,控制台输出
import java.util.Scanner;
public class Main1 {
static char [] status = new char [1000] ; //所用函数
static int times = 0 ; //变换的次数
static int depth = 1 ; //树的深度
public static int f(int i, int sum){
if(i == 0){ //执行f函数
return sum * 3 ;
}else{ //执行g函数
return sum / 2 ;
}
}
public static boolean backtrace(int n, int m, int currentDepth){
int sum = n ;
if(currentDepth> depth){ //当前深度不能是n变换为m
return false ;
}
for(int i=0; i<=1; i++){
sum = f(i, n) ;
if(sum == m || backtrace(sum, m, currentDepth+1)){ //回溯搜索
switch (i){
case 0 : status[times++] = 'f'; break ;
case 1 : status[times++] = 'g'; break ;
}
return true ;
}
}
return false ;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
int n = input.nextInt() ;
int m = input.nextInt() ;
while(!backtrace(n, m, 1)){
depth ++ ;
}
System.out.println(depth);
for(int i=0; i<times; i++){
System.out.print(status[i]);
}
}
}
方式2:文件流输入输出
import java.io.*;
public class Main2 {
static char [] status = new char [1000] ; //所用函数
static int times = 0 ; //变换的次数
static int depth = 1 ; //数的层数
static int n, m ;
public static int f(int i, int sum){
if(i == 0){ //执行f函数
return sum * 3 ;
}else{ //执行g函数
return sum / 2 ;
}
}
public static boolean backtrace(int n, int m, int currentDepth) {
int sum = n;
if (currentDepth > depth) { //当前深度不能是n变换为m
return false;
}
for (int i = 0; i <= 1; i++) {
sum = f(i, n);
if (sum == m || backtrace(sum, m, currentDepth + 1)) { //回溯搜索
switch (i) {
case 0:
status[times++] = 'f';
break;
case 1:
status[times++] = 'g';
break;
}
return true;
}
}
return false;
}
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream("D:\\study\\input.txt") ;
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(inputStream)) ;
String [] s = dataInputStream.readLine().split("[ ]") ;
n = Integer.parseInt(s[0]) ;
m = Integer.parseInt(s[1]) ;
while(!backtrace(n, m, 1)){
depth ++ ;
}
try(
FileOutputStream outputStream = new FileOutputStream("D:\\study\\output.txt") ;
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream)) ;) {
dataOutputStream.writeBytes(depth + "\n");
for (int i = 0; i < times; i++) {
dataOutputStream.writeBytes(status[i] + "");
}
}
}
}