李白打酒问题

</pre><pre class="cpp" name="code">

话说大诗人李白,一生好饮。幸好他从不开车。

    一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:

    无事街上走,提壶去打酒。
    逢店加一倍,遇花喝一斗。

    这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。

    请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。

    注意:通过浏览器提交答案。答案是个整数。不要书写任何多余的内容。
1.暴力求解

#include <stdio.h>
#include <math.h>
#include <string.h>

int main(){
	int i,j,k,temp,temps,tempf,c;
	int *a = new int[14];
	int flag,count=0;
	
	for(i=0;i<pow(2,14);i++){
		memset(a,0,sizeof(a));
		temps=tempf=0;c=2; 
		temp=i;//一种方案 
		
		for(j=0;j<14;j++){//将每次经过的地方,存入数组中 
			a[j]=temp%2;
			temp/=2;
		}
		
		
		for(k=0;k<14;k++){
			if(a[k]==1){//1代表遇见酒店 
				c*=2;
				temps++;
			}
			else{//0代表遇见花 
				c-=1;
				tempf++;
			}
				
		} 
		
		if(c==1 && temps==5 && tempf==9)
			count++;
		
	}
	printf("%d\n",count);
	return 0;
}


2.回溯法

一开始写的,因为忘记需要进行下一步判断,判断条件写错。

#include <stdio.h>
#include <math.h>
#include <string.h>
int a[14];
int count=0;
int temps=0,tempf=0,c=2;
void backtrace(int t,int s,int f,int c){
	if(t==13){
		if(s==5 && f==9 && c==1)
			{
				count++;
				
			}
	
	return;
	}
	else{
		a[t]=1;//遇见酒店
		backtrace(t+1,s+1,f,c*2);
		a[t]=0;

		backtrace(t+1,s,f+1,c-1); 
		
	}
}
int main(){
	backtrace(0,0,0,2);
	printf("%d",count);	
	return 0;
}

请教同学后。下面修正,添加了剪枝操作。

#include <stdio.h>
#include <math.h>
#include <string.h>
int a[14];
int count=0;
void backtrace(int t,int s,int f,int c){
	if(s>5 || f>9 || c<=0 )//剪枝 
    	return;
	if(t==14){
		if(s==5 && f==9 && c==1)
			{
				count++;
				
			}
	
	return;
	}
	else{
		a[t]=1;//遇见酒店
		backtrace(t+1,s+1,f,c*2);
		a[t]=0;

		backtrace(t+1,s,f+1,c-1); 
		
	}
}
int main(){
	backtrace(0,0,0,2);
	printf("%d",count);	
	return 0;
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值