The third of the recursive topic series, put apples
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
Put M identical apples on N identical plates, and allow some plates to be left empty. How many different ways are there in total? (represented by K) 5, 1, 1 and 1, 5, 1 are the same division.
Output:
For each set of input data M and N, use one line to output the corresponding K.
Sample Output:
20
8 Problem-
solving ideas:
Let f(m,n) be m apples and the number of ways to place n plates, then discuss n first:
①When m<n: there must be nm plates that are always empty, remove them and The number of ways to place apples has no effect. That is, if(n>m) f(m,n) = f(m,m);
②When m>=n: different placement methods can be divided into two categories:
1. At least one plate is empty, which is equivalent to f (m,n) = f(m,n-1);
2. All plates have apples, which is equivalent to removing one apple from each plate without affecting the number of different placement methods, that is, f(m,n ) = f(mn,n);
and the total number of ways to put apples is equal to the sum of the two, that is, f(m,n) =f(m,n-1)+f(mn,n).
Recursive exit condition description:
when n=1, all apples must be placed in a plate, so return 1;
when no apples can be placed, it is defined as one way of placing;
two recursive paths, the first n will be Gradually decrease, it will eventually reach the exit n==1;
the second m will gradually decrease, because when n>m, it will return f(m,m), so it will eventually reach the exit m==0.
Why export m==0? Because we always let m>=n to solve, so mn>=0, let m=0 end, if it is changed to m=1,
there may be a situation where mn=0 and the correct solution cannot be obtained.
AC code:
1 #include<bits/stdc++.h>
2 using namespace std;
3 int fun(int m,int n){
4 if(m==0 || n==1)return 1;
5 if(m<n)return fun(m,m);
6 else return fun(m,n-1)+fun(m-n,n);
7 }
8 int main(){
9 int t,m,n;
10 cin>>t;
11 while(t--){
12 cin>>m>>n;
13 cout<<fun(m,n)<<endl;
14 }
15 return 0;
16 }