Open Judge 1664 Placing apples

来源:互联网 发布:百合 知乎 编辑:程序博客网 时间:2024/06/06 02:51

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.



这道题的确有数学公式,但是!我们做的是搜索题。能用搜索解决的问题,为什么一定要去推数学公式呢?

首先要解决的就是重复问题,我的解决方案是让数组有序排列,这样就不会有重复情况了。

然后是dfs的退出条件,这里只要dfs到了(n+1)位就证明找到了吗?不一定!还要目前种的苹果总数达到m

同样的,要是目前苹果总数超过m,不用搜索了,直接退出好了。


#include<stdio.h>#include<string.h>#include<ctype.h>#include<iostream>#include<math.h>#include<algorithm>using namespace std;int ans,a[100];int t;int m,n;void dfs(int x){    int sum=0;    for(int i=1;i<x;i++)        sum+=a[i];    if(sum>m)        return ;    if((x==n+1)&&(sum==m))    {        ans++;        return ;    }    if(x==n+1)        return ;    for(int i=m;i>=0;i--)    {        if(i>=a[x-1])        {            a[x]=i;            dfs(x+1);            a[x]=-1;        }        else        {            return ;        }    }}int main(void){    //int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&m,&n);        memset(a,-1,sizeof(a));        ans=0;        dfs(1);        //printf("%d\n",t);        printf("%d\n",ans);    }    return 0;}

0 0
原创粉丝点击