码迷,mamicode.com
首页 > 其他好文 > 详细

POJ #1579 Function Run Fun

时间:2018-01-20 11:03:33      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:recursion   gpo   and   iostream   一个   思路   size   算法   else   

Description


 

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: 


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. 

 

题意


 

  现在有一个三元组(a, b, c),你要对 a、b、c 的大小进行分类讨论从而确定该三元组的值。这个算法很好实现,但是由于递归次数多所以执行时间很长。请你想一个执行时间尽可能短的办法来实现该算法。

 

Sample


 

  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.

  输入格式是三个整数组成的三元组,每个三元组占一行,直到读取到结束标志 -1 -1 -1 。输出格式直接看下面的图,我就不废话了。

  Input:

  技术分享图片

  output:

  技术分享图片

 

思路


 

  这道题需要解决的是递归中用时过多的问题,想想怎么样能少一点时间?那就是边递归边记录,已经记录的值就可以直接返回,这样就避免了递归时同一条数据的重复递归,这种技巧简称记忆化搜索。

  注意边界判断与递归顺序。

 

我的AC

#include<iostream>
using std::cin;
using std::cout;
using std::endl;

int getTripleVal(int , int , int ); //查询给定三元组的值
const int MAX = 21;
int w[MAX][MAX][MAX]; //记忆数组

int main(void) {
    int a, b, c;
    while (cin >> a >> b >> c) {
        if ( a == -1 && b == -1 && c == -1) {
            return 0;
        }
        else {
            int res = getTripleVal(a, b, c);
            cout << "w(" << a << ", " << b << ", " << c << ")" << " = " << res << endl;
        }
    }
    return 0;
}//main

int getTripleVal(int a, int b, int c) {
    if (a <= 0 || b <= 0 || c <= 0) {
        return w[0][0][0] = 1;
    }
    if (a >= MAX || b >= MAX || c >= MAX) {
        return getTripleVal(MAX-1, MAX-1, MAX-1);
    }
    
    // 在记忆数组中查询 w[a][b][c]的值,实现记忆化搜索
    if (w[a][b][c]) {
        return w[a][b][c];
    }

    //求出结果并保存
    if (a < b && b < c) {
        return w[a][b][c] = getTripleVal(a, b, c-1) + getTripleVal(a, b-1, c-1) - getTripleVal(a, b-1, c);
    }
    
    //求出结果并保存
    return w[a][b][c] = getTripleVal(a-1, b, c) + getTripleVal(a-1, b-1, c) + getTripleVal(a-1, b, c-1) - getTripleVal(a-1, b-1, c-1); 
}//getTripleVal

 

  

 

POJ #1579 Function Run Fun

标签:recursion   gpo   and   iostream   一个   思路   size   算法   else   

原文地址:https://www.cnblogs.com/Bw98blogs/p/8319889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!