Egyptian Fractions (HARD version) UVA

来源:互联网 发布:linux自动挂载硬盘 编辑:程序博客网 时间:2024/05/20 08:21

一道和紫书上原来的埃及分数差不多的题,就是加了一个判断条件,用这道题复习一下迭代加深搜索。


上代码:

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<set>using namespace std;typedef long long ll;ll gcd(ll a,ll b){    return b==0 ? a : gcd(b,a%b);}ll T,w;ll a,b;ll flag;ll maxd;ll out[10000000];ll ans[10000000];set<ll> used;bool better(ll d){    for(ll i=d;i>=0;i--)    {        if(ans[i]==out[i])continue;        return ans[i]==0 || out[i] < ans[i];    }    return false;}ll get_b(ll x,ll y){    ll c = y/x-3;    while(c*x<y)c++;    return c;}bool dfs(ll d,ll form,ll x,ll y){    if(d==maxd)    {        if(y%x) return false;        flag = 1;        if(used.find(y/x)!=used.end()) return false;        out[d] = y/x;        if(better(d)) memcpy(ans,out,sizeof(ll)*(d+1));        return true;    }    bool ok = false;     form = max(form, get_b(x,y));    ll cc = (maxd-d+1)*y;    for(ll t=form; ;t++)    {        if( cc <= x*t ) return ok;        if(used.find(t)!=used.end()) continue;        ll xx = t*x-y;        ll yy = t*y;        ll gg = 1;        out[d] = t;        gg = gcd(yy,xx);        if(dfs(d+1,t+1,xx/gg,yy/gg)) ok = true;    }    return ok;}void shuchu(){    printf("Case %lld: %lld/%lld=",w,a,b);    printf("1/%lld",ans[0]);    for(ll i=1; ;i++)    {        if(ans[i]==0)break;        printf("+1/%lld",ans[i]);    }    printf("\n");    return ;}int main(){    scanf("%lld" ,&T);    for(w=1 ; w<=T; w++)    {       scanf("%lld%lld" ,&a,&b);       flag = 0;       used.clear();       memset(out, 0,sizeof(out));       memset(ans,0,sizeof(ans));       ll num;       ll x;       scanf("%lld", &num);       while(num--) {scanf("%lld", &x); used.insert(x);}       for(maxd=1 ; ;maxd++)       {           memset(ans, 0, sizeof(ans));           if( dfs(0,get_b(a,b),a,b) ) break;       }       shuchu();    }    return 0;}
水波。