首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【HDU】1331 - Function Run Fun(记忆化递归)

【HDU】1331 - Function Run Fun(记忆化递归)

作者头像
FishWang
发布2025-08-27 11:50:58
发布2025-08-27 11:50:58
6000
代码可运行
举报
运行总次数:0
代码可运行

题目链接:点击打开题目

Function Run Fun

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 3922 Accepted Submission(s): 1918

Problem Description

We all love recursion! Don't we? Consider a three-parameter recursive function w(a, b, c): if a <= 0 or b <= 0 or c <= 0, then w(a, b, c) returns: 1 if a > 20 or b > 20 or c > 20, then w(a, b, c) returns: w(20, 20, 20) if a < b and b < c, then w(a, b, c) returns: w(a, b, c-1) + w(a, b-1, c-1) - w(a, b-1, c) otherwise it returns: w(a-1, b, c) + w(a-1, b-1, c) + w(a-1, b, c-1) - w(a-1, b-1, c-1) This is an easy function to implement. The problem is, if implemented directly, for moderate values of a, b and c (for example, a = 15, b = 15, c = 15), the program takes hours to run because of the massive recursion.

Input

The input for your program will be a series of integer triples, one per line, until the end-of-file flag of -1 -1 -1. Using the above technique, you are to calculate w(a, b, c) efficiently and print the result.

Output

Print the value for w(a,b,c) for each triple.

Sample Input

代码语言:javascript
代码运行次数:0
运行
复制

1 1 1 2 2 2 10 4 6 50 50 50 -1 7 18 -1 -1 -1

Sample Output

代码语言:javascript
代码运行次数:0
运行
复制

w(1, 1, 1) = 2 w(2, 2, 2) = 4 w(10, 4, 6) = 523 w(50, 50, 50) = 1048576 w(-1, 7, 18) = 1

Source

Pacific Northwest 1999

Recommend

Ignatius.L | We have carefully selected several similar problems for you: 1074 1078 1208 1355 1081

说白了就是动态规划的核心——记忆化搜索。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
LL num[22][22][22];
LL solve(int a,int b,int c)
{
	if (a <= 0 || b <= 0 || c <= 0)
		return 1;
	else if (a > 20 || b > 20 || c > 20)
		return solve(20,20,20);
	else if (num[a][b][c] != -1)		//记忆化搜索 
		return num[a][b][c];
	else if (a < b && b < c)
		return (num[a][b][c] = solve(a,b,c-1) + solve(a,b-1,c-1) - solve(a,b-1,c));
	else
		return (num[a][b][c] = solve(a-1,b,c) + solve(a-1,b-1,c) + solve(a-1,b,c-1) - solve(a-1,b-1,c-1));
}
int main()
{
	int a,b,c;
	while (~scanf ("%d %d %d",&a,&b,&c))
	{
		if (a == -1 && b == -1 && c == -1)
			break;
		CLR(num,-1);
		LL ans = solve(a,b,c);
		printf ("w(%d, %d, %d) = ",a,b,c);
		printf ("%lld\n",ans);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Function Run Fun
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档