HDU--1331 -- Function Run Fun -- memory-based search
Function Run FunTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission (s): 2376 Accepted Submission (s): 1187
Problem DescriptionWe 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.
InputThe 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.
OutputPrint the value for w (a, B, c) for each triple.
Sample Input
1 1 12 2 210 4 650 50 50-1 7 18-1 -1 -1
Sample Output
w(1, 1, 1) = 2w(2, 2, 2) = 4w(10, 4, 6) = 523w(50, 50, 50) = 1048576w(-1, 7, 18) = 1
The recursion that is modified for you enables him to process larger data.
Resolution: a, B, and c are controlled in 1 ~ 20, so you can use the memory-based search method to remember the data to prevent duplication.
# Include
# Include
# Include
Using namespace std; int dp [22] [22] [22], s = 0; // records prevent repeated searches for int w (int a, int B, int c) {if (a <= 0 | B <= 0 | c <= 0) return 1; if (a> 20 | B> 20 | c> 20) return w (20, 20); if (dp [a] [B] [c]) return dp [a] [B] [c]; // use the memory to prevent repeated if (
For some reason, I simply added the thought of memory to solve the problem. It was really nothing new !!