递归的函数 (动态规划)SDUT

版权声明:本人原创文章若需转载请标明出处和作者!沙 https://blog.csdn.net/weixin_44143702/article/details/89422136

递归的函数

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

给定一个函数 f(a, b, c):

如果 a ≤ 0 或 b ≤ 0 或 c ≤ 0 返回值为 1;

如果 a > 20 或 b > 20 或 c > 20 返回值为 f(20, 20, 20);

如果 a < b 并且 b < c 返回 f(a, b, c−1) + f(a, b−1, c−1) − f(a, b−1, c);

其它情况返回 f(a−1, b, c) + f(a−1, b−1, c) + f(a−1, b, c−1) − f(a-1, b-1, c-1)。

看起来简单的一个函数?你能做对吗?

Input

输入包含多组测试数据,对于每组测试数据:

输入只有一行为 3 个整数a, b, c(a, b, c < 30)。

Output

对于每组测试数据,输出函数的计算结果。

Sample Input

1 1 1
2 2 2

Sample Output

2
4
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int figure[35][35][35];///用来记录递归时计算过的值
int f(int, int, int);
int main()
{
    int a, b, c;
    memset(figure, -1, sizeof(figure));///注意此处是-1!
    while(~scanf("%d %d %d", &a, &b, &c))
    {///不要在while里面初始化figure数组,否则前面记录过的数据都没了!!!
        printf("%d\n", f(a, b, c));
    }
    return 0;
}
int f(int a, int b, int c)
{
    if(a <= 0 || b <= 0 || c <= 0)
        return 1;
    if(figure[a][b][c] != -1)///如果此值被记录过,则直接返回
        return figure[a][b][c];///这一个if很重要!!!如果不写就和普通递归没区别
    else if(a > 20 || b > 20 || c > 20)///在返回函数值的同时将其记录进数组
        return figure[a][b][c] = f(20, 20, 20);///在后面需要用的时候直接拿出来
    else if(a < b && b < c)///避免重复计算
        return figure[a][b][c] = f(a, b, c - 1) + f(a, b - 1, c - 1)
        - f(a, b - 1, c);
    else
        return figure[a][b][c] = f(a - 1, b, c) + f(a - 1, b - 1, c)
                                  + f(a - 1, b, c - 1) - f(a - 1, b - 1, c - 1);
}

猜你喜欢

转载自blog.csdn.net/weixin_44143702/article/details/89422136
今日推荐