博客
关于我
【紫书】UVA12558 埃及分数 Egyptian Fractions (HARD version)
阅读量:550 次
发布时间:2019-03-09

本文共 2090 字,大约阅读时间需要 6 分钟。

题目提交点

解题思路

这个题目数据范围有点小, 我刚开始想的是用dfs, 可是遇到了一些问题, 不知道他什么时候结束,最优解有几项,新加入的埃及分数取什么值最好等等问题困惑着我。

顺着理一下思路,需要暴力做这题,但是不知道上限,非常符合迭代加深搜的算法规则,OK,开始分析细节。

①迭代加深搜,搜到了就结束,没搜到就继续搜, dfs层数代表着埃及分数的项数。

②dfs剪枝, 层数超过了,或者累加的答案已经超过所要的答案了,进行剪枝操作。

③对埃及分数取值问题:

a, b 分别为已经累加到的数分子与分母,A, B分别为所需要的分子与分母。
设1/c 为所加的埃及分数, 便有
1/c + a / b <= A / B ==> 1/c <= A/B - a/b = (Ab - aB)/Bb ==> c >= Bb/(Ab - aB)
再与上一个已经取的值做比较,取最大,那么这个数就是最小的c值。

不一定这个最小的值是最好的,所以得不断的尝试, 让这个值自加。

设no 为最小的c的取值,max_d 为此dfs最大能到的层数, d 为当前层数。
当这个新取的埃及分数小到无论怎么取都达不到的值时,结束此埃及分数的取值,即 a/b + (max_d - d) / no < A / B

代码

#include
#include
using namespace std;#define _for(i, a, b) for (int i = (a); i < (b); ++i)#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)typedef long long LL;int A, B;unordered_set
R;inline int readint(){ int x; scanf("%d", &x); return x;}LL gcd(LL a, LL b){ return b ? gcd(b, a % b) : a;}LL get_first(LL a, LL b, LL last){ return max((B * b) / (A * b - a * B), last + 1);}bool judge(const vector
& D, const vector
& ans){ if (ans.empty()) return true; for (int i = ans.size() - 1; ~i; --i) if (D[i] != ans[i]) return D[i] < ans[i]; return false;}void dfs(LL a, LL b, const int d, const int max_d, vector
& D, vector
& ans){ if (d > max_d) return; if (a * B > A * b) return; if (a == A && b == B) { if (judge(D, ans)) ans = D; return; } LL no = get_first(a, b, D.empty() ? 1LL : D.back()); while (true) { if (a * B * no + (max_d - d) * B * b < A * b * no) break; if (!R.count(no)) { LL na = a * no + b, nb = b * no, g = gcd(na, nb); D.push_back(no); dfs(na / g, nb / g, d + 1, max_d, D, ans); D.pop_back(); } no++; }}int main(){ #ifdef LOCAL freopen("data.in", "r", stdin);#endif int T = readint(); _rep(kase, 1, T) { A = readint(), B = readint(); int k = readint(); R.clear(); _for(i, 0, k) R.insert(readint() * 1LL); for (int d = 2; ; ++d) { vector
D, ans; dfs(0, 1, 0, d, D, ans); if (!ans.empty()) { printf("Case %d: %d/%d=", kase, A, B); int sz = ans.size(); _for(i, 0, sz)printf("1/%lld%s", ans[i], (i == sz - 1) ? "\n" : "+"); break; } } } return 0;}

转载地址:http://qmzpz.baihongyu.com/

你可能感兴趣的文章
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>
mysql 索引类型以及创建
查看>>
MySQL 索引连环问题,你能答对几个?
查看>>