整数变换问题

整数变换问题

        

        关于整数i的变换fg定义如下:f(i)=3ig(i)=ëi/2û

试设计一个算法,对于给定的2个整数nm,用最少的变换次数将n变成m

样例输入

15 4

样例输出

4
gfgg


解:

整数变换问题:
利用回溯写变换,因为不清楚回溯的终点在哪,所以人为规定变换次数在100次以内

从n开始,当t==m时代表n已经变换成m,此时判断当前状态的变换次数与当前最小次数比较,
进行变换次数以及变换方式路径的记录

在回溯过程中每层都有两种情况,f 或者是 g,
使用标记数组记录当前路径,设 f 为 1 ,g 为 2;
当所有情况考虑完成之后,输出最小变换次数以及变换路径(题目要求倒序输出)。 


#include <stdio.h>
int m;
int tempcount,bestcount;
int temp1[100]={0};
int temp2[100]={0};
void dfs(int t)
{
	if(t==m){
		if(tempcount<bestcount){
			bestcount=tempcount;
			for(int i=1;i<=bestcount;i++)
			{
				temp2[i]=temp1[i];
			}
		}
		return;
	}
	
	
	int temp=t/2;
	tempcount++;
	if(tempcount<bestcount&& t>0){
		temp1[tempcount]=1;
		dfs(temp);
		
	}
	tempcount--;
	
	temp=3*t;
	tempcount++;
	if(tempcount<bestcount){
		temp1[tempcount]=2;
		dfs(temp);
	}
	tempcount--;
	
	
}

int main()
{
	int n;
	scanf("%d %d",&n,&m);
	tempcount=0;
	bestcount=100;
	dfs(n);
	printf("%d\n",bestcount);
	for(int i=bestcount;i>=1;i--){
		if(temp2[i]==2)
			printf("f");
		if(temp2[i]==1)
			printf("g");
	}
	printf("\n");
	return 0;
 } 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值