来源: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;
}