整数变换问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
整数变换问题。关于整数i的变换f和g定义如下:f(i)=3i;![]()
试设计一个算法,对于给定的2 个整数n和m,用最少的f和g变换次数将n变换为m。例如,可以将整数15用4 次变换将它变换为整数4:4=gfgg(15)。当整数n不可能变换为整数m时,算法应如何处理?
对任意给定的整数n和m,计算将整数n变换为整数m所需要的最少变换次数。
Input
输入数据的第一行有2 个正整数n和m。n≤100000,m≤1000000000。
Output
将计算出的最少变换次数以及相应的变换序列输出。第一行是最少变换次数。第2 行是相应的变换序列。
Sample Input
15 4
Sample Output
4 gfgg
Hint
Source
#include <iostream>
using namespace std;
int k = 1;
int c = 0;
char a[100] = {'\0'};
int SelectFun(const int n, const int m, int s) //选择函数
{
if(s == 0){
return 3 * n;
}
else{
return n / 2;
}
}
bool DeptSearch(int Dept, const int n, const int m)//深搜
{
int num;
if(Dept > k) return false;
num = n;
for(int i = 0; i < 2; i++)
{
num = SelectFun(n, m, i);
if(num == m || DeptSearch(Dept + 1,num,m)){
if(i == 0){
a[c] = 'f';
}
else{
a[c] = 'g';
}
c ++;
return true;
}
}
return false;
}
int main()
{
int m, n, Dept = 1;
cin >> m >> n;
k = 1;
while( !DeptSearch(1, m, n) )
{
k ++;
}
cout << k << endl;
int i = 0;
for(i = 0; i < c; i ++){
cout << a[i];
}
return 0;
}
1345

被折叠的 条评论
为什么被折叠?



