UVA 12558(p216)----Eg[y]ptian Fractions(HARD version)

#include<set>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define debu
using namespace std;
typedef long long LL;
const int maxn=10000;
set<LL> flag;
LL a,b,c,k,cas=0;
LL ans[maxn];
LL v[maxn];
LL gcd(LL a,LL b)
{
    return b==0?a:gcd(b,a%b);
}
LL better(LL d)
{
    for(LL i=d; i>=0; i--)
        if(v[i]!=ans[i])
            return ans[i]==-1||v[i]<ans[i];
    return 0;
}
LL get_first(LL a,LL b)
{
    return b/a+1;
}
int dfs(LL d,LL from,LL a,LL b,LL maxd)
{
    if(d==maxd)
    {
        if(b%a) return 0;
        if(flag.count(b/a)) return 0;
        v[d]=b/a;
        if(better(d)) memcpy(ans,v,sizeof(LL)*(d+1));
        return 1;
    }
    int ok=0;
    from=max(from,get_first(a,b));
    for(LL i=from;; i++)
    {
        if(b*(maxd+1-d)<=i*a) break;
        if(flag.count(i)) continue;
        v[d]=i;
        LL bb=b*i;
        LL aa=a*i-b;
        LL g=gcd(aa,bb);
        if(dfs(d+1,i+1,aa/g,bb/g,maxd)) ok=1;
    }
    return ok;
}
void solve()
{
    LL ok=0,maxd;
    for(maxd=1;; maxd++)
    {
        memset(ans,-1,sizeof(ans));
        if(dfs(0,get_first(a,b),a,b,maxd))
        {
            ok=1;
            break;
        }
    }
    for(LL i=0; i<=maxd-1; i++)
        printf("1/%lld+",ans[i]);
    printf("1/%lld\n",ans[maxd]);
}
void init()
{
    flag.clear();
    memset(v,0,sizeof(v));
}
int main()
{
#ifdef debug
    freopen("in.in","r",stdin);
    freopen("out.out","w",stdout);
#endif // debug
    int t;
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%lld%lld%lld",&a,&b,&k);
        printf("Case %lld: %lld/%lld=",++cas,a,b);
        for(LL i=0; i<k; i++)
        {
            int x;
            scanf("%d",&x);
            flag.insert(x);
        }
        solve();
    }
    return 0;
}

你可能感兴趣的:(UVA 12558(p216)----Eg[y]ptian Fractions(HARD version))