POJ1579.Function Run Fun,funrun

來源:互聯網
上載者:User

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;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.