UVA12558 埃及分数 Egyptian Fractions (HARD version)【迭代加深搜索】

E g y p t i a n   F r a c t i o n s   ( H A R D   v e r s i o n ) Egyptian\ Fractions\ (HARD\ version) Egyptian Fractions (HARD version)

题意:

把a/b写成不同的埃及分数之和,要求项数尽可能小,在此前提下的最小的分数尽量大,然后第二小的分数尽可能大…还有k个数不能用做分母,要求输出最优解。(埃及分数就是分子为1的分数)

TJ:

由于a/b写成埃及分数形式有无数多种,直接用dfs暴力搜是搜不完的,而题目要求项数少,这样可以用迭代加深搜索来做,每次限制深度,也就是项数,搜就完事儿了。
注意每次开始搜索的分母大小还有剪枝的条件

#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> pll;
const int maxn = 1111;
LL ans[maxn],A[maxn];
int cant[maxn];
pll goal;
int n,maxd,k;
LL gcd(const LL &a,const LL &b){
	return b?gcd(b,a%b):a;
}
pll sub(const pll &a,const pll &b){				//分数相减+约分
	LL tmp = a.second*b.second/gcd(a.second,b.second);
	LL ta = a.first*(tmp/a.second);
	LL tb = b.first*(tmp/b.second);
	LL del = gcd(abs(ta-tb),tmp);
	return make_pair((ta-tb)/del,tmp/del);
}
bool better(){								//判断是否比当前解更优
	if(ans[maxd]==0) return true;
	for(int i=maxd;i>=1;i--){
		if(A[i]!=ans[i]){
			if(A[i]>ans[i]) return false;
			else return true;
		}
	}
}
bool dfs(pll now,int dep,int curi){
	if(dep==maxd){
		if(now.first!=1) return false;
		if(now.second<=1000&&cant[now.second]) return false;
		A[maxd] = now.second;
		if(better()) memcpy(ans,A,sizeof(A));
		return true;
	}
	bool ok = false;
	for(int i=max((LL)curi,now.second/now.first+1);;i++){
		if(sub(now,make_pair(maxd-dep+1,i)).first>=0) break;
		if(i<=1000&&cant[i]) continue;
		A[dep] = i;
		if(dfs(sub(now,make_pair(1,i)),dep+1,i+1)) ok = true;
	}
	return ok;
}
int main(){
	scanf("%d",&n);
	for(int kase=1;kase<=n;kase++){
		memset(ans,0,sizeof(ans));
		scanf("%lld %lld",&goal.first,&goal.second);
		scanf("%d",&k); memset(cant,0,sizeof(cant));
		while(k--){
			int pos;
			scanf("%d",&pos);
			cant[pos] = 1;
		}
		for(maxd=1;;maxd++) if(dfs(goal,1,2)) break;
		printf("Case %d: %lld/%lld=",kase,goal.first,goal.second);
		for(int i=1;i<=maxd;i++){
			printf("1/%lld",ans[i]);
			if(i!=maxd) printf("+");
			else printf("\n");
		}
	}
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值