zoukankan      html  css  js  c++  java
  • poj1579

    Function Run Fun
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 15623   Accepted: 8080

    Description

    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: 


    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. 

    Input

    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.

    Output

    Print the value for w(a,b,c) for each triple.

    Sample Input

    1 1 1
    2 2 2
    10 4 6
    50 50 50
    -1 7 18
    -1 -1 -1

    Sample Output

    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


    思路:若直接用递归,肯定会超时,需要用三维数组进行记忆化,减少时间。
     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<string.h>
     4 using namespace std;
     5 int dp[22][22][22];
     6 int DFS(int a,int b,int c)
     7 {
     8     if(dp[a][b][c]!=-1)
     9         return dp[a][b][c];
    10     if(a<=0||b<=0||c<=0)
    11         return 1;
    12     else if(a>20||b>20||c>20)
    13         return DFS(20,20,20);
    14     else if(a<b&&b<c)
    15         return DFS(a, b, c-1) + DFS(a, b-1, c-1) - DFS(a, b-1, c);
    16     else
    17         return DFS(a-1, b, c) + DFS(a-1, b-1, c) + DFS(a-1, b, c-1) - DFS(a-1, b-1, c-1);
    18 }
    19 int main()
    20 {
    21     int a,b,c,i,j,k;
    22     memset(dp,-1,sizeof(dp));
    23     for(i=0; i<=20; i++)
    24         for(j=0; j<=20; j++)
    25             for(k=0; k<=20; k++)
    26                 dp[i][j][k]=DFS(i,j,k);
    27     while(cin>>a>>b>>c)
    28     {
    29         if(a==-1&&b==-1&&c==-1)
    30             break;
    31         if(a<=0||b<=0||c<=0)
    32             printf("w(%d, %d, %d) = 1
    ",a,b,c);
    33         else if(a>20||b>20||c>20)
    34             printf("w(%d, %d, %d) = %d
    ",a,b,c,dp[20][20][20]);
    35         else
    36             printf("w(%d, %d, %d) = %d
    ",a,b,c,dp[a][b][c]);
    37     }
    38     return 0;
    39 }
    View Code
  • 相关阅读:
    shopping car 1.0
    文件分类
    求1-100的所有数的和
    输出 1-100 内的所有奇数和
    求1-2+3-4+5 ... 99的所有数的和
    关闭提示的下拉框
    h5页面乱码-设置编码
    常用的css
    渲染后新元素没有绑定事件
    爬虫日记-关于一些动态爬取
  • 原文地址:https://www.cnblogs.com/lxm940130740/p/3671902.html
Copyright © 2011-2022 走看看