POJ1579.Function Run Fun,funrun
試題請參見: http://poj.org/problem?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 ) { return 1; } 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 a = 0, b = 0, c = 0; while ( std::cin >> a >> b >> c ) { if ( a == -1 && b == -1 && c == -1 ) { break; } std::cout << "w(" << a << ", " << b << ", " << c << ")" << " = " << w(a, b, c) << std::endl; } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。