4:Placing apples
-
总Time Limit:
- 1000ms Memory Limit:
- 65536kB
-
Description
-
We are going to place M same apples into N same plates.
There could be some empty plates.
How many methods do we have?
When we have 7 applesand 3 plates, the methods, (1, 5, 1) and (5, 1, 1) are the same.
Input
-
The first line is the number of test cases, t. 0<=t<=20
The next t lines are test cases containing two numbers, M and N. 1<=M, N<=10.
Output
- Output the numbers of method in each test case in one line. Sample Input
-
17 3
Sample Output
-
8
-
题解:有m个苹果,n个盘子,刚开始的时候,是按先只能放一个盘子,然后只能放了两个盘子来想的,但发现这样太复杂,很难找的规律。
后来看了书,发现我们可以这样想,不管有几个苹果,几个盘子,都能分为两种情况 1:至少有一个盘子为空,不放苹果,2:每个盘子都放苹果,所以总数为两种情况相加,因为每个盘子都放苹果的种数与有m-n个苹果放到n个盘子里是一样的,所以如果我们令总数为f(n,m),则f(n,m)=f(n-1,m)+f(n,m-n),要注意的是,如果m<n,则一定有n-m个盘子是空的,所以我们把空的盘子去掉,既当n>m时f(n,m)=f(m,m)以此类推,所以我们可以用递归来接这道题;
递归调用的函数为:
int kind(int n, int m)
{
if(n<m)
return kind(m,m);
if(n==1||m==0)
return 1;
return kind(n-1,m)+kind(n,m-n);
}
完整代码如下
#include<stdio.h>
int kind(int m,int n)
{
int ans;
if(n>m){
return kind(m,m);
}
else if(n==1||m==0){
return 1;
}
return kind(m,n-1)+kind(m-n,n);
}
int main()
{
int n,num,m,i;
scanf("%d",&num);
while(num--){
scanf("%d %d",&m,&n);
printf("%d\n",kind(m,n));
}
return 0;
}
因为n减一,有值为一的时候,我们一直控制着m>=n,有m==0的时候,这两种情况都返回1;