POJ-1163 DP三角形

                                                 The Triangle

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 63359   Accepted: 37940

     Description

7
3   8
8   1   0
2   7   4   4
4   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

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

Sample Output

30

 

 

动态规划起源于《运筹学》的内容,

 

 

 

Source

IOI 1994

 

 

 

 

 

 

 

 

动态规划程序设计是对解最优化问题的一种途径、一种方法,而不是一种特殊算法。

基本模型

(1)确定问题的决策对象。

(2)对决策过程划分阶段。

(3)对各阶段确定状态变量。

(4)根据状态变量确定费用函数和目标函数。

(5)建立各阶段状态变量的转移过程,确定状态转移方程。

附:状态转移方程的一般形式:

一般形式: U:状态; X:策略
      顺推:f[Uk]=opt{f[Uk-1]+L[Uk-1,Xk-1]} 其中, L[Uk-1,Xk-1]: 状态Uk-1通过策略Xk-1到达状态Uk 的费用 初始f[U1];结果:f[Un]。

倒推:
  f[Uk]=opt{f[Uk+1]+L[Uk,Xk]}
  L[Uk,Xk]: 状态Uk通过策略Xk到达状态Uk+1 的费用
  初始f[Un];结果:f(U1)

 

 

 

采用顺推阶段 ,从尾到头进行状态转移。

 

F[n] = Opt{F[[n - 1] + L{n - 1,Xn - 1}}

初始:

F[n + 1] = 0

结果:

F[0]

 

import java.util.Scanner;
import java.math.*;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int m;
		Scanner sc = new Scanner(System.in);
		int [][]a = new int[120][120];
		m = sc.nextInt();
		int n;
		for(int i = 0;i < m;++i)
		{
			for(int j = 0;j <= i;++j)
			{
				n= sc.nextInt();
				a[i][j] = n;
			}
		}
		for(int i = 0;i < m;++i)
		{
			a[m][i] = 0;
		}//Fk+1 = 0
		for(int i = m;i >= 1;--i)
		{
			for(int j = 0;j <= m;++j)
			{
				a[i - 1][j] = Math.max(a[i][j] + a[i - 1][j], a[i][j + 1] + a[i - 1][j + 1]);
			}
		}
		System.out.println(a[0][0]);
	}

}

 

 

你可能感兴趣的:(动态规划)