Integer transformation problem-backtracking method

Integer transformation problem: The transformation f and g of integer i are defined as follows: f(i)=3i; g(i)=i/2. Try to design an algorithm, for a given 2 integers n and m, use the least number of transformations of f and g to transform n to m. For example, you can transform the integer 15 into an integer 4: 4=gfgg(15) with 4 transformations. What should the algorithm do when it is impossible to transform the integer n into the integer m?


This is a variant of the 3n+1 problem. In order to find the shortest transformation sequence, a step-by-step deepening backtracking search is used.

The development environment is vs2013, c++ language

Algorithm steps:
1. Get the number n to be transformed and the number m to be transformed from the keyboard.
2. Set the number of transformation k to 1, and use search(1, n) to perform a backtracking search. If it is found, output the result ; Otherwise, increment k once and continue searching until the maximum number of transformations is found or exceeded.
3. search (dep, n) recursive backtracking search, each time 3*n and n/2, and continue from these two branches to two branches, until it finds or exceeds the limit.
4. Algorithm time complexity: Because it is a sorting tree, it is O(n!)

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"iostream"
using namespace std;

static int n;//要变换的数
static int m;//要变换成的数
static int k;//变换的次数
static bool found;//查找结果
static int result[100];//最多变换100次

bool search(int dep, int n);
void compute();
int fg(int n, int i);

void compute(){
	k = 1;
	found = false;
	while (!search(1, n)){
		k++;
		if (k > 100)
			break;
		if (found)
			break;
	}
}

bool search(int dep, int n){
//search实现回溯搜索
	if (dep>k){
		return false;
	}
	for (int i = 0; i<2; i++){
		int num = n;
		num = fg(num, i);
		result[dep] = i;
		if (num == m || search(dep + 1, num)){
			found = true;
			return true;
		}
	}
	return false;
}

int fg(int n, int i){
	if (i == 0)
		return n / 2;
	else
		return 3 * n;
}

void main(){
	cout << "输入要变换的数: ";
	cin >> n ;
	cout << "输入要变换成的数: ";
	cin >> m ;
	for (int i = 0; i<99; i++){
		result[i] = 0;
	}
	compute();
	if (found){
		cout << "运算次数:" << k << "次" << endl;
		cout << "运算过程:";
		for (int i = k; i >= 1; i--){
			if (result[i] == 0)
				cout << "g";
			else if (result[i] == 1)
				cout << "f";
		}
		cout << endl;	
	}
	else{
		cout <<n<<"无法变换成"<<m <<endl;
	}
	system("pause");
}

Guess you like

Origin blog.csdn.net/u014377853/article/details/49998281