Function Run Fun
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
1 1 1
2 2 2
10 4 6
50 50 50
-1 7 18
-1 -1 -1
Sample Output
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
翻译:
我们都喜欢递归!不是吗?
考虑一个三参数递归函数w(a,b,c):
如果a<=0或b<=0或c<=0,则w(a,b,c)返回:1
如果a>20或b>20或c>20,则w(a,b,c)返回:w(20,20,20)
如果a<b和b<c,则w(a,b,c)返回:w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c)
否则返回:w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1)
这是一个易于实现的功能。问题是,如果直接实现,对于a、b和c的中等值(例如,a=15,b=15,c=15),由于大量递归,程序需要几个小时才能运行。
输入
程序的输入将是一系列整数三元组,每行一个,直到文件结束标志-1-1-1为止。使用上述技术,您将有效地计算w(a,b,c)并打印结果。
输出
打印每个三元组的w(a,b,c)值。
题意: 非常明显这是一道递归的题,就是求出递归后的答案.
思路: 直接递归的话应该会T(我没试过,看题得出的结论),所以我们可以用记忆化,这道题直接记忆化一下就完成了.
AC代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
int vis[105][105][105];
int fun(int a,int b,int c)
{
if(a<=0||b<=0||c<=0)
return 1;
if(vis[a][b][c])
return vis[a][b][c];
if(a>20||b>20||c>20)
return vis[20][20][20]=fun(20,20,20);
return vis[a][b][c]=fun(a-1,b,c)+fun(a-1,b-1,c)+fun(a-1,b,c-1)-fun(a-1,b-1,c-1);
}
int main()
{
int x,y,z;
while(~scanf("%d%d%d",&x,&y,&z))
{memset(vis,0,sizeof(vis));
if(x==-1&&y==-1&&z==-1)
return 0;
printf("w(%d, %d, %d) = %d\n",x,y,z,fun(x,y,z));
}
}