整數變換問題

整數變換問題

        

        關於整數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;
 } 


發佈了161 篇原創文章 · 獲贊 70 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章