Loj10022 埃及分数(迭代加深搜索IDDFS)

#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
typedef long long ll;

ll depth,a,b,flag,ans[100005],nans[100005];

inline ll gcd(ll a,ll b){ return b?gcd(b,a%b):a; }

inline void yuefen(ll &a,ll &b){ll eaa=gcd(a,b);a/=eaa;b/=eaa;}

inline void dfs(ll now,ll shen_fz,ll shen_fm,ll last_fm){
    yuefen(shen_fz,shen_fm);//在上面统一约分多省事啊哈哈哈
    if(now==depth){
        if(shen_fz==1&&shen_fm>last_fm){
            if(flag&&shen_fm>=ans[depth])return;//要比较取优,因为最大的分母是算出来的不是搜出来的
            nans[depth]=shen_fm;
            flag=1;
            memcpy(ans,nans,sizeof(nans));
        }
        return;
    }
    for(ll i=last_fm+1;i<=ceil((double)(depth-now+1)*shen_fm/shen_fz);i++){
            //i=last_fm+1使搜出来的分母递增,所以说都是要这样搜啊QAQ
            //(depth-now+1)*shen_fm/shen_fz是趋近的最大值,即限制能否在depth内把shen的分数拆分完
            //其实好像可以判断一下就是(i>=shen_fm/shen_fz才可以),跟最后一个注释同理,亲测确实快一点
        nans[now]=i;
        dfs(now+1,shen_fz*i-shen_fm,shen_fm*i,i);
    }
}

int main(){
    scanf("%I64d%I64d",&a,&b);//好吧其实在loj上忘了改成lld
    while(++depth){
        dfs(1,a,b,b/a-1);//b/a是第一个分母的最小值,第一个分母不用从1开始搜的
        if(flag){
            for(ll i=1;i<=depth;i++)printf("%I64d ",ans[i]);
            return 0;
        }
    }
}

好吧算是比较易懂了

参考文献:https://blog.csdn.net/Clove_unique/article/details/53169537

转载于:https://www.cnblogs.com/Y15BeTa/p/loj10022.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值