Apple Divide Algorithm

Topic content:
Put M identical apples on N identical plates, and allow some plates to be left empty. How many different ways are there in total? M, N are natural numbers. Explanation: If there are 7 apples and 2 plates, then (5, 1, 1) and (1, 5, 1) and (1, 1, 5) are the same division method.
enter description
The first line is an integer representing the number of groups of data (multiple groups of data). For each group of data, the first line is the number of apples M (1 ≤ m ≤ 100), and the second line is the number of plates N (1 ≤ n ≤ 100 ).

output description
Each group of data is output one line, and the number of ways to put apples.

input sample
1
3
2

Sample output

2

/*
Idea 1:
122 212 221 is the same method, then take the table 221
123.321 is the same method, then take the representative 321
The characteristic of a combination that can be used as a "representative" is that the former is not smaller than the latter.
This is a limitation.
It's best to use recursion after thinking about it.
For example, put 10 into 3 baskets and become:
Put 10 in the first one, then put 0 in the remaining 2 baskets
Put 9 in the first one, then put 1 in the remaining 2 baskets
Put 8 in the first one, then put 2 in the remaining 2 baskets
Put 7 in the first one, then put 3 in the remaining 2 baskets
.
In short, M apples, N baskets,
The first put a, the range of a is reduced from M to 0,
And then put (Ma) apples into N-1 baskets.
But when putting it, it must satisfy "the front is not smaller than the back".

Idea 2:
f(m, n) means putting m apples into n plates
f(10,3) = f(10, 2) + f(7, 3)
10 apples in 3 trays = 10 apples in 2 trays (there is an empty tray, and there is one tray left)
+ 7 apples into 3 plates (there is no empty plate, put an apple in each plate first, only 7 apples are left )
Then recursively, the following algorithm is solved according to idea 2
*/

#include<stdio.h>  
int fun(int m,int n){   
    if(m==0||n==1)    
        return 1;     
    if(n>m)  
        return fun(m,m);  //如果前面的小于后面的,则一定会有空盘子,则等于m个苹果放入m个盘子 
    else  
        return fun(m,n-1)+fun(m-n,n);  //有空盘子的情况 + 没有空盘子的情况 
}  
int main(){  
    int t,m,n;  
    scanf("%d",&t);  
    while(t--){     
        scanf("%d%d",&m,&n);  
        printf("%d\n",fun(m,n));  
    }  
    return 0;  
}  


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325786570&siteId=291194637