题目描述 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
数据范围及提示 Data Size & Hint
0<a<b<=1000
题解:迭代加深搜
首先迭代加深确定深度(分数个数最小)
然后在确定的深度进行搜索,搜索可行解的最优解(最小的分数最大)
每次需要确定当前搜索的分母的范围,如果还要选x个,当前剩余a/b,然后在平均分的情况下为a/(b*x),因为是分母所以最大为(b*x)/a
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 2003
#define LL long long
using namespace std;
LL ans[N],now[N],a,b;
int n;
bool pd;
LL gcd(LL x,LL y)
{
LL r;
while (y){
r=x%y;
x=y;
y=r;
}
return x;
}
void yuefen(LL &a,LL &b)
{
LL c=gcd(a,b);
a/=c; b/=c;
}
void dfs(int x,LL pre,LL a,LL b)
{
if (a<1) return;
LL nowa=a; LL nowb=b;
yuefen(nowa,nowb);
if (x==1) {
if (nowa==1&&nowb>pre) {
if (pd&&nowb>=ans[1]) return ;
now[1]=nowb; pd=1;
for (int i=1;i<=n;i++) ans[i]=now[i];
}
return;
}
LL maxn=ceil((double)nowb*x/(double)nowa);
for (int i=pre;i<=maxn;i++) {
now[x]=i;
dfs(x-1,i,nowa*i-nowb,nowb*i);
}
}
int main()
{
freopen("a.in","r",stdin);
scanf("%I64d%I64d",&a,&b);
n=1; pd=false;
yuefen(a,b); //cout<<a<<" "<<b<<endl;
while (!pd) {
dfs(n,1,a,b);
n++;
}
for (int i=n-1;i>=1;i--)
printf("%I64d ",ans[i]);
putchar('\n');
}