1. 程式人生 > >Loj10022 埃及分數(叠代加深搜索IDDFS)

Loj10022 埃及分數(叠代加深搜索IDDFS)

flag gcd name 親測 scan 比較 inline 限制 space

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

好吧算是比較易懂了

Loj10022 埃及分數(叠代加深搜索IDDFS)