试题请参见: ?id=1579
题目概述
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.
解题思路
非常简单的递推, 并且已经给出了状态转移方程.
我们要做的就是Copy it. 但是有一个问题, 我们需要记录每一次计算的结果, 以免重复计算造成TLE.
遇到的问题
我写错了判断条件你敢信!! (请注意是a <= 0而不是a < 0).
源代码#include <iostream>const int MAX_SIZE = 21;int table[MAX_SIZE][MAX_SIZE][MAX_SIZE] = {0};int w(int a, int b, int c) {if ( a <= 0 || b <= 0 || c <= 0 ) {} else if ( a > 20 || b > 20 || c > 20 ) {return w(20, 20, 20);}if ( table[a][b][c] == 0 ) {if ( a < b && b < c ) {table[a][b][c] = w(a, b, c – 1) + w(a, b – 1, c – 1) – w(a, b – 1, c);} else {table[a][b][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);}}return table[a][b][c];}int main() {int cin >> a >> b >> c ) {if ( a == -1 && b == -1 && c == -1 ) {break;}std::cout << “w(” << a << “, ” << b << “, ” << c << “)”<< ” = ” << w(a, b, c) << std::endl;}}
,人之所以能,是相信能。