您的位置:首页 > 其它

POJ1664 放苹果(dfs)

2018-01-31 09:08 459 查看

Description

把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法。

Input

第一行是测试数据的数目t(0 <= t <= 20)。以下每行均包含二个整数M和N,以空格分开。1<=M,N<=10。

Output

对输入的每组数据M和N,用一行输出相应的K。

Sample Input

1
7 3


Sample Output

8


思路

一共有两种情况,令f(m,n)f(m,n)表示把mm个苹果放在nn个盘子里的分法数。那么当苹果数为0或者剩下一个盘子,只有一种分法,返回1,当盘子数量比苹果数量多时,相当于把mm个苹果放在mm个盘子中,对于其他情况:①至少空出一个盘子不放(相对于目前),则转化为在(n-1)个盘子里放m个苹果,在剩下的盘子里放入0个苹果,即f(m,n−1)f(m,n−1)②所有盘子至少放入一个。先在每个盘子里都放入1个苹果,剩下m-n个苹果,再在n个盘子里进行放置。即f(m−n,n)f(m−n,n)

代码

#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
#define inf 1000000
#define mem(a,b) memset(a,b,sizeof(a))
int dfs(int m,int n)
{
if(m==0||n==1)
return 1;
if(n>m)
return dfs(m,m);
return dfs(m,n-1)+dfs(m-n,n);
}
int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
printf("%d\n",dfs(m,n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: