Bailian1664 Placing apples【递推+记忆化递归】

1664:Placing apples
总时间限制: 1000ms 内存限制: 65536kB
描述
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.
输入
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 the numbers of method in each test case in one line.
样例输入
1
7 3
样例输出
8

问题链接Bailian1664 Placing apples
问题描述:(略)
问题分析
    这个问题的关键是递推函数。
m个苹果放在n个盘子中,那么定义函数为apple(m,n):
1.m=0,没有苹果,那么只有一种放法,即apple(0,n)=1
2.n=1,只有一个盘中,不论有或者无苹果,那么只有一种放法,apple(m,1)=1
3.n>m,和m个苹果放在m个盘子中是一样的,即apple(m,n)=apple(m,m)
4.m>=n,这时分为两种情况,一是所有盘子都有苹果,二是不是所有盘子都有苹果。不是所有盘子都有苹果和至少有一个盘子空着是一样的,即=apple(m,n-1)。所有盘子都有苹果,也就是至少每个盘子有一个苹果,m个苹果中的n个放在n个盘子中,剩下的m-n个苹果,这和m-n个苹果放在n个盘子中是是一样的,即=apple(m-n, n)。这时,apple(m,n)=apple(m-n, n)+apple(m,n-1)。
    本题采用记忆化递归的解法。
    这个题也可以用母函数来解,是一个母函数的裸题。
程序说明
    本题与参考链接是同一题,使用参考链接的程序提交就AC了。
参考链接POJ1664 放苹果【递推+记忆化递归】
题记:朋友交多了,容易遇见熟人。

AC的C语言程序如下:

/* POJ1664 放苹果 */

#include <stdio.h>
#include <string.h>

#define N 10
int a[N + 1][N + 1];

int apple(int m, int n)
{
    if(a[m][n])
        return a[m][n];
    else {
        if(m == 0 || n == 1)
            return a[m][n] = 1;
        else if(n > m)
            return a[m][n] = apple(m, m);
        else
            return a[m][n] = apple(m - n, n) + apple(m, n - 1);
    }
}

int main(void)
{
    memset(a, 0, sizeof(a));

    int t, m, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &m, &n);

        printf("%d\n", apple(m, n));
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tigerisland45/p/10166475.html