Poj 1163 the triangle)

Source: Internet
Author: User

The triangle
Time limit:1000 ms   Memory limit:10000 K
Total submissions:38195   Accepted:22946

Description

73 88 1 02 7 4 44 5 2 6 5 (figure 1)
Figure 1 shows a number triangle. write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. each step can go either diagonally down to the left or diagonally down to the right.

Input

Your program is to read from standard input. the first line contains one integer N: the number of rows in the triangle. the following n lines describe the data of the triangle. the number of rows in the triangle is> 1 but <= 100. the numbers in the triangle, All integers, are between 0 and 99.

Output

Your program is to write to standard output. The highest sum is written as an integer.

Sample Input

573 88 1 0 2 7 4 44 5 2 6 5

Sample output

30
Question:

In the preceding digital triangle, find a path from the bottom edge of the top to make
The sum of the numbers passed by the path is the largest. Each step in the path can only be left down or
Bottom right. You only need to find the largest sum and do not need to provide a specific path.
The number of triangle rows is greater than 1 and less than or equal to 100, and the number is 0-99

It's Super classic. You can see it when you understand it...

Solution:
Use a two-dimensional array to store digital triangles.
D (R, j): number J of row R (R, J starts from 1)
Maxsum (R, j): from the paths of D (R, j) edges,
The sum of the numbers in the optimal path.
Problem: Calculate maxsum)
Typical recursion problems.
D (R, J). The next step can only be d (R + 1, J) or D (R + 1, J + 1 ). Therefore, for triangles with N rows:
If (r = N)
Maxsum (R, j) = D (R, J)
Else
Maxsum (R, j) = max {maxsum (R + 1, J), maxsum (R + 1, J + 1)} + d (R, J)

Recursive program for digital triangles:

#include <iostream>#include <algorithm>#define MAX 101using namespace std;int D[MAX][MAX];int n;int MaxSum(int i, int j){if(i==n)return D[i][j];int x = MaxSum(i+1,j);int y = MaxSum(i+1,j+1);return max(x,y)+D[i][j];}int main(){int i,j;cin >> n;for(i=1;i<=n;i++)for(j=1;j<=i;j++)cin >> D[i][j];cout << MaxSum(1,1) << endl;}


Why timeout?
Answer: Repeated computing
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
If you use the delivery method to traverse each path in depth, there is a large
Repeated computing. The time complexity is 2 N, for n = 100
Line, certainly timeout.

For example, when we calculate the length of the third row, because the generation of 8 1 0 is based on the "7" position of the fourth row, that is, d [4] [2], there are 1*2*3 paths in front of the path search, which will be calculated 6*2 times = 12 times again.

Considering that removing duplicates will greatly improve the program running efficiency. So how to do it ???

If every maxsum (R, j) is calculated, it is saved.
You can directly use the value to avoid repeated calculation. So
You can use O (N 2) time to complete the computation. Because the total number of triangles
The number is n (n + 1)/2.

Recursive animation program for digital triangles:

#include <iostream>#include <algorithm>using namespace std;#define MAX 101int D[MAX][MAX]; int n;int maxSum[MAX][MAX];int MaxSum(int i, int j){if( maxSum[i][j] != -1 )return maxSum[i][j];if(i==n) maxSum[i][j] = D[i][j];else {int x = MaxSum(i+1,j);int y = MaxSum(i+1,j+1);maxSum[i][j] = max(x,y)+ D[i][j];}return maxSum[i][j];}int main(){int i,j;cin >> n;for(i=1;i<=n;i++)for(j=1;j<=i;j++) {cin >> D[i][j];maxSum[i][j] = -1;}cout << MaxSum(1,1) << endl;}


If you assign values to maxsum [N] [J] at the bottom layer, You can continuously roll out maxsum [1] [1].






Recursive dynamic program:

#include <iostream>#include <algorithm>using namespace std;#define MAX 101int D[MAX][MAX]; int n;int maxSum[MAX][MAX];int main() {int i,j;cin >> n;for(i=1;i<=n;i++)for(j=1;j<=i;j++)cin >> D[i][j];for( int i = 1;i <= n; ++ i )maxSum[n][i] = D[n][i];for( int i = n-1; i>= 1; --i )for( int j = 1; j <= i; ++j )maxSum[i][j] = max(maxSum[i+1][j],maxSum[i+1][j+1]) + D[i][j]cout << maxSum[1][1] << endl;}

Space optimization:

There is no need to use a two-dimensional maxsum array to store each maxsum (R, J), as long as one row from the underlying row up
Recursive, as long as the one-dimensional array maxsum [100], that is, as long as the maxsum value of a row is stored
Yes.

Think about it: the specific situation is as follows: select the largest of the adjacent two and add d [I] [J], the new value will be stored in the array and overwrite the first adjacent number. Each time an I loop is passed, the number of values overwritten by the array will gradually decrease, we know that the second row overwrites the first row, that is, the first array d [1]. you will find that only the nth number in the array has not changed ,,


Check the Code:

#include <iostream>#include <algorithm>using namespace std;#define MAX 101int D[MAX][MAX]; int n;int maxSum[MAX];int max(int a,int b){return a>b?a:b;}int main() {int i,j;cin >> n;for(i=1;i<=n;i++)for(j=1;j<=i;j++)cin >> D[i][j];for(i = 1;i <= n; ++ i )maxSum[i] = D[n][i];for(i = n-1; i>= 1; --i )for(j = 1; j <= i; ++j )maxSum[j] = max(maxSum[j],maxSum[j+1]) + D[i][j];cout << maxSum[1] << endl;return 0;}

For further consideration, you can use
Line n replaces maxsum.
Space-saving, time complexity unchanged

Check the Code:

#include <iostream>#include <algorithm>using namespace std;#define MAX 101int D[MAX][MAX];int n; int * maxSum;int main(){int i,j;cin >> n;for(i=1;i<=n;i++)for(j=1;j<=i;j++)cin >> D[i][j];maxSum = D[n]; //maxSum指向第n行for( int i = n-1; i>= 1; --i )for( int j = 1; j <= i; ++j )maxSum[j] = max(maxSum[j],maxSum[j+1]) + D[i][j];cout << maxSum[1] << endl;}

General idea of solving dynamic regulation problems
1. Break down the original problem into subproblems
Shard splits the original problem into several subproblems, which are in the same form as the original problem.
Or similar, but the scale is smaller. All sub-problems are solved. The original problem is solved.
(Digital triangle example ).
The solution of the  subproblem is saved once it is obtained. Therefore, each subproblem only needs
Solution once.

2. Confirm the status
When we use dynamic planning to solve problems, we often associate it with sub-problems.
A set of values of each variable is called a "shape
Status ". A "status" corresponds to one or more sub-problems,
The "value" under a "status" is like this.
State.

2. Confirm the status
All "status" sets constitute the "status space" of the problem ". "Status
The size of space is directly related to the time complexity of solving the problem using dynamic planning.
In the example of a digital triangle, a total of N x (n + 1)/2 numbers, so this
There are N x (n + 1)/2 states in the status space of the problem.
The time complexity of the entire problem is the number of states multiplied by the number of States required to calculate each State.
Time.
In a digital triangle, each "state" only needs to go through once, and
The time taken for calculation in the state is a constant irrelevant to n.

2. Confirm the status
When using dynamic planning to solve problems, it is often the case that K integer variables can
Form a State (such as the row number and column number in a digital triangle)
Constitute a "status "). If the values of these K integer variables are
N1, N2 ,...... So we can use a K-dimensional array.
Array [N1] [n2]... [NK] to store the "value" of each State ". This
"Value" may not be an integer or floating point number, but may need a structure.
Array can be a structure array. One
The "value" under "status" is usually the solution to one or more sub-problems.

3. Determine the values of some initial states (boundary states)
Taking the "digital triangle" as an example, the initial state is the bottom side number, Value
It is the base side numeric value.

4. determine the state transition equation
After defining the "status" and the "value" under the "status ",
Find out how different states are migrated-that is, how one or more "values" are known
"Status" to find the "value" of another "status" ("everyone else" recursive type ). Status
The state transition can be expressed by a recursive formula, which can also be called a "state transition party ".
".
State transition equation of a digital triangle:


Features of problems solved with Dynamic Rules
1) The problem has the optimal substructure. If the optimal solution includes
The solution to a subproblem is also optimal. We call this problem an optimal subknot.
Structure.
2) No aftereffect. The following process is performed once several status values are determined.
The evolution is only related to the values of these States.
Means or the path that passes through to the current status, no
Yes.

Poj 1163 the triangle)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.