1008 Putting Apples

来源:互联网 发布:长板空间 淘宝 编辑:程序博客网 时间:2024/06/05 15:14

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. }  

原创粉丝点击