1008 Putting Apples

1008 Putting Apples

Putting Apples

时间限制: 1秒  内存限制: 64M

Problem Description

If we have n apples and k baskets, and we want to put all the apples into the baskets. We can leave some baskets empty. Now we want to know how many different ways we can put the apples. Be careful, the baskets are same, so {1,2} and {2, 1} are the same way.

Input

This problem contains multiple test cases.

For each test case, there are two integers n and k (1 <= n, k<= 100).

Output

For each test case, please output the number of ways we can put the apples.

Sample Input

7 3

2 1

Sample Output

8

1

一开始用的模拟,由于重复计算导致了超时

后来看了张伟大学霸的报告然后查了查书之后知道了一下两点:

1、为了避免重复计算,要将已算出的会被重复使用的数据保存

2、篮子多苹果少时,模拟会将其作为不同情况进行计算。因此要将多出的篮子放弃,看作是苹果和篮子数量相同来计算

3、苹果多篮子少时,可以认为是一下两种情况的和

    I. 每个篮子放一个,剩下的苹果按照篮子为空正常计算

    II.一个篮子为空,剩下的篮子正常计算 

即 d[n][k] = d[n-k][k] + d[n][k-1] 。此时n-k可正可负可为零,因此要分别对待,否则会造成re

n-k == 0 时,可以后退为 d[n][n] 的值,即 1 + d[n][k-1]

n-k < 0 时,可以后退为 d[n][k] 的 k > n 的情况,然后作为 d[n][n] 处理,因此可以被回避。


  1. #include<stdio.h>  
  2. #include<string.h>  
  3. int d[110][110];  
  4. int find(int n,int k)  
  5. {  
  6.     if ( d[n][k] != -1 ) return d[n][k];  
  7.     if ( n == 0 ) return 1;  
  8.     if ( k == 1 || n == 1 )   
  9.     {  
  10.         d[n][k] = 1;  
  11.         return 1;  
  12.     }  
  13.     if ( n < k ) k = n;  
  14.     d[n][k] = find(n-k,k) + find(n,k-1);  
  15.     return d[n][k];  
  16. }  
  17. int main()  
  18. {  
  19.     int n,k;  
  20.     while ( scanf("%d%d",&n,&k) != -1 )  
  21.     {  
  22.         memset(d,-1,sizeof(d));  
  23.         if ( k > n ) k = n;  
  24.         if ( d[n][k] == -1 ) d[n][k] = find(n,k);  
  25.         printf("%d\n",d[n][k]);  
  26.     }  
  27.     return 0;  
  28. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值