#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;
const int MAX = 50;
int n, m;
int x[MAX];
int bestx[MAX];
int f(int i, int n)
{
if(i==1)
return n*3;
else
return n/2;
}
int k; //搜索深度,逐步加深
bool found = false;
bool backtrack(int dep, int n)
{
if(dep > k)
return false;
else
{
for(int i=1; i<=2; i++)
{
int temp = f(i, n);
x[dep] = i;
if(temp == m || backtrack(dep+1, temp))
{
found = true;
for(int j=1; j<=k; j++)
bestx[j] = x[j];
return true;
}
x[dep] = 0;
}
}
return false;
}
void search()
{
k = 1;
while(!backtrack(1, n))
{
k++;
memset(x, 0, sizeof(x));
memset(bestx, 0, sizeof(bestx));
}
}
int main()
{
ifstream fin("整数变换.txt");
cout << "输入正整数n:";
fin >> n; cout << n;
cout << "\n输入正整数m:";
fin >> m; cout << m << endl;
search();
if(found)
{
cout << n << "变为" << m << "最少的变换次数为:" << k << endl;
cout << "变换过程为:";
for(int i=1; i<=k; i++)
if(bestx[i] == 1)
cout << 'f';
else
cout << 'g';
}
else
cout << "变换失败!\n";
cout << endl << endl;
return 0;
}
整数变换问题
最新推荐文章于 2021-11-06 17:08:59 发布