uva12558
思路
IDDFS+减枝
- 当1/x * (剩余的层数) < a/b 减枝continue
- 当1/x > a/b 减枝continue
- 当出现第一组答案时,如果x>ans[deep-1] ,此时已经不是最优解了,减枝continue
- 坑:能用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;
}