博客
关于我
【紫书】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索引类型
查看>>
MySQL索引背后的数据结构及算法原理
查看>>
mysql索引能重复吗_mysql “索引”能重复吗?“唯一索引”与“索引”区别是什么?...
查看>>
Mysql索引(4):索引语法
查看>>
mysql级联删除_Mysql笔记系列,DQL基础复习,Mysql的约束与范式
查看>>
mysql经常使用命令
查看>>
MySQL经常使用技巧
查看>>
mysql给账号授权相关功能 | 表、视图等
查看>>
MySQL缓存使用率超过80%的解决方法
查看>>
Mysql缓存调优的基本知识(附Demo)
查看>>
mysql网站打开慢问题排查&数据库优化
查看>>
mysql网络部分代码
查看>>
mysql联合索引的最左前缀匹配原则
查看>>
mysql自动化同步校验_Shell: 分享MySQL数据同步+主从复制自动化脚本_20190313_七侠镇莫尛貝...
查看>>
mysql自增id超大问题查询
查看>>
MySQL自带information_schema数据库使用
查看>>
MySQL获取分组后的TOP 1和TOP N记录
查看>>
mysql虚拟列表_动态网页制作-官方版合集下载-多特
查看>>
MySQL蜜罐反制获取攻击者信息
查看>>
Mysql表创建外键报错
查看>>