2016夏季练习——搜索

来源:UVA12588

埃及分数

搜索神题之一(IDDFS):

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
LL del[10];
long long a,b,k;
int maxdep;
bool flag;
LL ans[10010];
LL temp[10010];
int cnt;
LL gcd(LL a,LL b){
	if(b==0) return a;
	return gcd(b,a%b);
}
bool better(){//判断是否是最好的情况
	for(int i=maxdep;i>=0;i--){
		if(temp[i]!=ans[i])
			return temp[i]<ans[i];
	}
	return 0;
}
bool find(LL a){//找到这个数字的所在位置
	for(int i=0;i<k;i++)
		if(del[i]==a) return 1;
	return 0;
}
void IDDFS(int floor,LL a,LL b){//a/b//IDDFS搜索
	if(floor==maxdep){
		if(b%a) return ;
		temp[floor]=b/a;
		if(find(b/a)) return ;
		if(!flag||better())
			memcpy(ans,temp,sizeof(LL)*(floor+1));
		flag=1;
		return ;
	}
	LL aa,bb,dd;
	for(int i=max(b/a,temp[floor-1])+1;;i++){
		if(b*(maxdep+1-floor)<=i*a) break;
		if(find(i))continue;
		aa=a*i-b;
		bb=b*i;
		dd=gcd(aa,bb);
		temp[floor]=i;
		IDDFS(floor+1,aa/dd,bb/dd);
	}
}
void print(int nc){//打印函数
	cout<<"Case "<<nc++<<": "<<a<<"/"<<b<<"=1/"<<ans[0];
	for(int i=1;i<=maxdep;i++)
		cout<<"+1/"<<ans[i];
	cout<<endl;
}
int main(){
	int T;
	scanf("%d",&T);
	int nc=1;
	while(T--){
		scanf("%lld%lld%lld",&a,&b,&k);
		memset(ans,-1,sizeof(ans));
		memset(temp,0,sizeof(temp));
		int d;
		for(int i=0;i<k;i++){
			scanf("%d",&del[i]);
		}
		//cout<<a<<" "<<b<<" "<<(b-1)/a+1<<endl;
		flag=0;
		maxdep=0;
		while(1){
			maxdep++;//最大深度
			flag=0;
			IDDFS(0,a,b);
			if(flag) break;
		}
		print(nc);
		nc++;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值