uva12558

uva12558

思路

IDDFS+减枝

  1. 当1/x * (剩余的层数) < a/b 减枝continue
  2. 当1/x > a/b 减枝continue
  3. 当出现第一组答案时,如果x>ans[deep-1] ,此时已经不是最优解了,减枝continue
  4. 坑:能用bool的就不要用int

代码

#include <stdio.h>
#include <string.h>

typedef long long ll;
const int maxk = 1010;
ll ans[10], now[10];
ll a, b;
int kn;
bool k[maxk];// 不要使用int类型,会超时,这个就离谱
ll gcd(ll n1, ll n2)
{
    ll temp;
    while (n1 != 0)
    {
        temp = n1;
        n1 = n2 % n1;
        n2 = temp;
    }
    return n2;
}
int ok = 0;
int ans_size;
void dfs(int limit, ll cnta, ll cntb)
{
    if (cntb % cnta == 0 && cntb / cnta > now[ans_size - 2] && (cntb / cnta > 1000 || !k[cntb / cnta]))
    {
        now[ans_size - 1] = cntb / cnta;
        bool aa = 0;
        for (int i = ans_size - 1; i >= 0; i--)
        {
            if (now[i] < ans[i])
            {
                aa = 1;
                break;
            }
            else if (now[i] > ans[i])
                break;
        }
        if (!ok || aa)
            memcpy(ans, now, sizeof(now));
        ok = 1;
        return;
    }
    ll s = cntb / cnta;
    ll t = (limit * cntb) / cnta;
    if (s == 1)
        s = 2;
    if (s <= now[ans_size - limit - 1])
        s = now[ans_size - limit - 1] + 1;
    if (ok && t > ans[ans_size - 1])
        t = ans[ans_size - 1] - 1;
    for (ll i = s; i <= t; i++)
    {
        if (i <= 1000 && k[i])
            continue;

        ll g = gcd(cnta * i - cntb, cntb * i);
        now[ans_size - limit] = i;
        dfs(limit - 1, (cnta * i - cntb) / g, cntb * i / g);
    }
    return;
}
void print_ans()
{
    ok = 0;
    for (ans_size = 2;; ans_size++)
    {
        dfs(ans_size, a, b);
        if (ok)
        {
            printf("%lld/%lld=1/%lld", a, b, ans[0]);
            for (int i = 1; i < ans_size; i++)
            {
                printf("+1/%lld", ans[i]);
            }
            printf("\n");
            return;
        }
    }
    return;
}
int main()
{
    freopen("./in.txt", "r", stdin);
    freopen("./out.txt", "w", stdout);
    int t;
    scanf("%d", &t);
    int kase = 0;
    while (t--)
    {
        scanf("%lld %lld %d", &a, &b, &kn);
        memset(k, 0, sizeof(k));
        int kk;
        for (int i = 0; i < kn; i++)
        {
            scanf("%d", &kk);
            k[kk] = 1;
        }
        printf("Case %d: ", ++kase);
        print_ans();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值