当前位置: 代码迷 >> 综合 >> CODEVS 1288 埃及分数
  详细解决方案

CODEVS 1288 埃及分数

热度:67   发布时间:2023-12-13 18:54:55.0

题目描述 Description
在古埃及,人们使用单位分数的和(形如1/a的, a是自然数)表示一切有理数。 如:2/3=1/2+1/6,但不允许2/3=1/3+1/3,因为加数中有相同的。 对于一个分数a/b,表示方法有很多种,但是哪种最好呢? 首先,加数少的比加数多的好,其次,加数个数相同的,最小的分数越大越 好。 如: 19/45=1/3 + 1/12 + 1/180 19/45=1/3 + 1/15 + 1/45 19/45=1/3 + 1/18 + 1/30, 19/45=1/4 + 1/6 + 1/180 19/45=1/5 + 1/6 + 1/18. 最好的是最后一种,因为1/18比1/180,1/45,1/30,1/180都大。 给出a,b(0 < a < b < 1000),编程计算最好的表达方式。
输入描述 Input Description
a b
输出描述 Output Description
若干个数,自小到大排列,依次是单位分数的分母。
样例输入 Sample Input
19 45
样例输出 Sample Output
5 6 18


剪枝:

  1. 以递增顺序搜索。
  2. (a/b)/lft>1/i
  3. 如果当前i大于ans末尾,return

分数 加减很麻烦。


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int l;
long long ans[1005],tmp[1005];
bool flg;
void dfs(long long a,long long b,int lft)
{if(lft==0){if(a==0){flg=1;if(tmp[l]<ans[l])for(int i=1;i<=l;i++)ans[i]=tmp[i];}return ;}if((b*lft)/a>ans[l]||tmp[l-lft]>ans[l])return ;for(long long i=max(tmp[l-lft]+1,b/a);i<=(b*lft)/a;i++){tmp[l-lft+1]=i;if(a*i<b)continue;dfs((a*i-b),i*b,lft-1);}
}
int main()
{long long a,b;scanf("%lld%lld",&a,&b);memset(ans,0x3f,sizeof(ans));for(int i=1;;i++){l=i;dfs(a,b,i);if(flg){for(int j=1;j<=i;j++)printf("%lld ",ans[j]);printf("\n");break;}}return 0;
}