Dynamic Programming: Multi-stage decision, every step to solve the problem is the problem of sub-problems later stages of solving, decision-making each step will depend on the results of the decision of the previous step. (It can be used for combinatorial optimization problems)
Optimization principle: any sub-optimal decision sequence a sequence itself must be the optimal decision sequence corresponds to sequence the initial and final states.
Only problem optimization principles to meet before they can take advantage of a dynamic algorithm to solve, because only the global optimum solution equal to each of its sub-optimal problem can be solved in stages.
7Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
Input
Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Output
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
Hint
7The highest score is achievable by traversing the cows as shown above.
*
3 8
*
8 1 0
*
2 7 4 4
*
4 5 2 6 5
#include <the iostream>
#include <CString>
the using namespace STD;
const int MAXN = 355;
int main ()
{
int SUM = 0, A [MAXN] [MAXN], B [MAXN] [MAXN], C [MAXN] [maxn]; // a record number for each position of the cow, b [i] [j] from the record (i, j) position of the maximum number and go down but does not include a [i] [j] itself
int n ;
CIN >> n-;
for (int I =. 1; I <= n-; I ++)
for (int J =. 1; J <= I; J ++)
Scanf ( "% D", & A [I] [J]); // store each cow number
for (int. 1-n-= I; I> =. 1; i--)
{
for (int. 1 = J; J <= I; J ++)
{
IF (a [I +. 1] [j] + b [i + 1] [j]> = a [i + 1] [j + 1] + b [i + 1] [j + 1]) b [i] [j] = b [i +1] [j] + a [ i + 1] [j], c [i] [j] = 0; // c records the path taken
else b [i] [j] = b [i + 1] [ . 1 + J] + a [I +. 1] [+ J. 1], C [I] [J] =. 1;
}
}
/ * COUT << a [. 1] [. 1] << endl; // commented the contents of the path taken
for (int i = 1, j = 1; i <n;i++)
{
cout<<a[i+1][j+c[i][j]]<<endl;
j=j+c[i][j];
}*/
cout<<a[1][1]+b[1][1]<<endl;
return 0;
}