题目链接:http://bailian.openjudge.cn/practice/1579?lang=en_US
总时间限制:
1000ms
内存限制:
65536kB
描述
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.
输入
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.
输出
Print the value for w(a,b,c) for each triple.
样例输入
1 1 1 2 2 2 10 4 6 50 50 50 -1 7 18 -1 -1 -1
样例输出
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
分析:题就不多说了,按要求求解。我谈一下我的思路,因为要用到递归,所以对子状态的处理要注意下细节,也就是要避免重复计算子状态(这个怎么理解呢?比如你某一次程序递归已经递归到最底层,然后开始打上记忆化向上回溯。回溯时又可能沿着不同方向进行,可能又遇到相同的子状态,这个时候还需要在递归吗?可以是可以,当问题规模很大的时候,会TLE,程序可能还得跑半天才可能出结果),我开个记忆化数组,初始化为-1(0也可以,不过-1更保险些),这样每次递归调用的时候我判断下记忆化数组的这个值是否为-1,不是的话,说明已经计算过了,这个时候直接返回到上一层。
这样操作下来的话时间会优化很多很多,大家试一下就知道了,下面我贴上自己的代码:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
typedef long long ll;
int a,b,c;
int d[21][21][21]; //该数组做记忆化数组,防止相同的子状态重复递归
ll fun(int a,int b,int c)
{
if(a<=0 || b<=0 || c<=0)
return 1;
else if(a>20 || b>20 || c>20)
return fun(20,20,20);
else if(a<b && b<c)
{
if(d[a][b][c] != -1)
return d[a][b][c];
return d[a][b][c] = fun(a,b,c-1) + fun(a,b-1,c-1) - fun(a,b-1,c);
}
else
{
if(d[a][b][c] != -1)
return d[a][b][c];
return d[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()
{
ios::sync_with_stdio(false);
while(cin>>a>>b>>c)
{
if(a==-1 && b==-1 && c==-1)
break;
memset(d,-1,sizeof d); //我习惯将记忆化数组初始化为-1
cout<<"w("<<a<<','<<' '<<b<<','<<' '<<c<<')'<<' '<<'='<<' ';
cout<<fun(a,b,c)<<endl;
}
return 0;
}