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;
}