动态规划:多阶段决策问题,每步求解的问题是后面阶段问题求解的子问题,每步决策将依赖于以前步骤的决策结果。(可以用于组合优化问题)
优化原则:一个最优决策序列的任何子序列本身一定是相当于子序列初始和结束状态的最优决策序列。
只有满足优化原则的问题才可以利用动态算法进行求解,因为只有全局最优解法等于其每个子问题的最优才可以分阶段进行求解。
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Then 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.
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
7
*
3 8
*
8 1 0
*
2 7 4 4
*
4 5 2 6 5
The highest score is achievable by traversing the cows as shown above.
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=355;
int main()
{
int sum=0,a[maxn][maxn],b[maxn][maxn],c[maxn][maxn]; //a记录每个位置牛的编号 ,b[i][j]记录从(i,j)位置往下走的最大编号和但不包括a[i][j]本身
int n;
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
scanf("%d",&a[i][j]); //存储每头牛的编号
for(int i=n-1;i>=1;i--)
{
for(int j=1;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记录走的路径
else b[i][j]=b[i+1][j+1]+a[i+1][j+1],c[i][j]=1;
}
}
/*cout<<a[1][1]<<endl; //注释掉的内容所走的路径
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;
}