例7-2埃及分数(迭代加深搜索)

题目:

样例输入 Sample Input

19 45

样例输出 Sample Output

5 6 18

思路:

参考文章链接:

https://www.cnblogs.com/hchlqlz-oj-mrj/p/5389223.html

https://blog.csdn.net/never__give__up/article/details/78448743

而这题用浮点数存储分数的话会有各种奇怪的错误,所以我们可以用两个数a,b分别表示分数的分子和分母。

在搜索时,我们记录前几层搜索后所剩下的分数la/lb(即a/b-1/x1-1/x2-...

由于题目中要求最大分母最小,且与此同时分母的字典序要最小,由于我们枚举时就是按字典序查找的,所以我们不用考虑字典序的问题,而最大分母最小这一个条件很好判断,有更好解的时候直接替换即可。

Gcd辗转相除法

两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。

a = kb + rabkr皆为正整数,且r<b),则r = a mod b

假设da,b的一个公约数

而r = a - kb,两边同时除以d,r/d=a/d-kb/d=m,可知m为整数

因此d也是b,a mod b的公约数

 

约分,限制分数个数(迭代)-深度搜索(当前分母数cur+)

剪枝条件(depth-step)*1/i>la/lb//=?

x/y=la/lb-1/i=(la*i-lb)/(lb*i)

分母的搜索范围:

要大于上一层的分母,所以枚举时要从max(上一层分母+1,lb/la)开始搜索(要注意lb/la的计算)。如果a=1,b%a!=0,直接是埃及分数,否则b/a+1,因为不等,必然有舍,舍后+1为最小分母

剪枝条件:

depth-cur*1/start<=a/b

b*(depth-cur)<=a*start

计算剩余数x/y=a/b-1/start通分

a/b-1/start=(a*start)/(b*start)-b/(b*start)=(a*start-b)/(b*start),所以x=(a*start-b)y=(b*start)。要注意约分

代码:

/*
19 45
3 4

*/
#include<stdio.h>
#include<string.h>
#define MAX 100
int depth=0;
int temp[MAX];
int ans[MAX];
bool flag=0;
int gcd(int a,int b){
	if(!b)return a;
	else return gcd(b,a%b);
}
void dfs(int a,int b,int cur){
//	printf("a:%d b:%d cur:%d\n",a,b,cur);
	
	if(cur+1==depth){
		if(a==1){
//			cur++;
			temp[cur+1]=b;//mark 
			printf("end depth:%d\n",b) ;
			if(temp[cur+1]<ans[cur+1]||ans[cur+1]==0){//解更优则替换 
				memcpy(ans,temp,sizeof(temp));
				flag=1;
			}
//			return OK;
		}else{
			printf("useless:%d!=1\n",a);
//			return CONTINUE;
		}
		return; 
	}
	int start;
	if(b%a==0)start=b/a;//如果la=1,lb%la!=0,直接是埃及分数
	else start=b/a+1;//因为不能整除,必然有舍,舍后+1为最小分母
	//floor+0.5不能用,不是四舍五入,必须大于等于 
	if(temp[cur]+1>start)start=temp[cur]+1;
	while(1){
		if(b*(depth-cur)<=a*start){//剪枝条件
//			printf("break:a:%d b%d i:%d\n",a,b,start);
			printf("%d*(%d-%d)<%d*%d\n",b,depth,cur,a,start);
			break;
		}
		printf("%d*(%d-%d)>%d*%d\n",(int)b,(int)depth,(int)cur,(int)a,(int)start);
		temp[cur+1]=start; //cur下次循环也要用,只有递归下一层才能+ 
		int tempa=a*start-b;
		int tempb=b*start;
		int g=gcd(tempa,tempb);
		for(int i=0;i<depth;i++){//mark
			printf("%d ",temp[i]);
		}
		printf("\n");
		printf("i:%d \n",start);
		dfs(tempa/g,tempb/g,cur+1);
		start++;
	}
//	return CONTINUE;//这里直接确定返回值会改变原值 
}
int main(){
	int a,b;
	int g;//公约数 
	scanf("%d%d",&a,&b);
	g=gcd(a,b);
	a/=g;
	b/=g;
	temp[0]=1;
	while(++depth){
		printf("\ndepth:%d\n",depth);
		dfs(a,b,0);
		if(flag)break;//mark
	}
	for(int i=1;i<=depth;i++){//mark
		printf("%d ",ans[i]);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值