Description
给定一个分数,问用分子为1的分数加和来构成这个分数有多少种方式。要求每种情况分数的个数不超过n,分母乘积不超过a
Input
多组用例,每组用例包括四个整数p,q,a,n分别表示给出分数的分子,分母,组成该分数的数个分数的分母乘积上限与个数上限,以0 0 0 0结束输入
Output
对于每组用例,输出满足条件的方法数
Sample Input
2 3 120 3
2 3 300 3
2 3 299 3
2 3 12 3
2 3 12000 7
54 795 12000 7
2 3 300 1
2 1 200 5
2 4 54 2
0 0 0 0
Sample Output
4
7
6
2
42
1
0
9
3
Solution
简单dfs,dfs(now,son,mother,cnt,res),其中now表示当前可以用的分母值,son和mother表示当前分数值的分子与分母,cnt表示当前分分数个数,res表示当前分数的分母乘积,注意几步剪枝
1.分母乘积大于a(等于也可能符合条件不能剪)
2.分数的个数已经大于等于n
3.当前分数值已经大于目标分数值
Code
#include<stdio.h>
int p,q,n,a,ans;
void dfs(int now,int son,int mother,int cnt,int res)
{
if(p*mother==q*son&&mother){ans++;return ;}
if(res>a)return ;
if(cnt>=n)return ;
if(p*mother<q*son)return ;
int tson,tmother;
if(mother) tson=son*now+mother,tmother=mother*now;
else tson=1,tmother=now;
if(res*now<=a)dfs(now,tson,tmother,cnt+1,res*now);
if(res*(now+1)<=a)dfs(now+1,son,mother,cnt,res);
}
int main()
{
while(~scanf("%d%d%d%d",&p,&q,&a,&n),p||q||n||a)
{
ans=0;
dfs(1,0,0,0,1);
printf("%d\n",ans);
}
return 0;
}