简单版和加强版的区别就是数据范围扩大到了long long,并且加了限制条件。用IDA*算法即可解决。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL maxd, ans[10240], v[10240];
set<LL> ban;
LL gcd(LL a, LL b){
return b ? gcd(b, a % b) : a;
}
inline LL get_first(LL a, LL b){
return b/a + 1;
}
bool better(int d){
for(int i = d; i >= 0; --i)
if(v[i] != ans[i])
return ans[i]==-1 || v[i]<ans[i];
return false;
}
bool DFS(int d, LL from, LL aa, LL bb)
{
if(d == maxd){
if(bb % aa || ban.count(bb/aa)) return false;
v[d] = bb / aa;
if(better(d))
memcpy(ans, v, sizeof(LL)*(d+1));
return true;
}
bool ok = false;
from = max(from, get_first(aa, bb));
for(LL i = from; ; ++i){
if(ban.count(i)) continue;
if(bb * (maxd+1-d) <= i * aa) break;
v[d] = i;
LL b2 = bb * i, a2 = aa * i - bb;
LL g = gcd(a2, b2);
if(DFS(d+1, i+1, a2/g, b2/g)) ok = true;
}
return ok;
}
int main()
{
int T; cin >> T;
for(int t = 1; t <= T; ++t){
int a, b, n;
cin >> a >> b >> n;
ban.clear();
while(n--){
int x; cin >> x;
ban.insert(x);
}
for(maxd = 1; ; ++maxd){
memset(ans, -1, sizeof(ans));
if(DFS(0, get_first(a, b), a, b))
break;
}
printf("Case %d: %d/%d=1/%lld", t, a, b, ans[0]);
for(int i = 1; i <= maxd; i++)
printf("+1/%lld", ans[i]);
printf("\n");
}
return 0;
}