poj 1163 The Triangle(dp)
The Triangle
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 43993 | Accepted: 26553 |
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
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
第一道DP题,水过,纪念一下~
Java AC 代码
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int rows = sc.nextInt(); int input[][] = new int[rows + 1][rows + 1]; int result[][] = new int[rows + 1][rows + 1]; //将每个点的最大结果存在数组里 for(int i = 1; i <= rows; i++) for( int j = 1; j <= i; j++) { input[i][j] = sc.nextInt(); } result[1][1] = input[1][1]; dp(input, result); int max = Integer.MIN_VALUE; for(int i = 1; i <= rows; i++) { //找出最后一行最大的一个,即为结果 if(result[rows][i] > max) max = result[rows][i]; } System.out.println(max); } public static void dp(int[][] input, int[][] result) { int rows = input.length - 1; for(int i = 2; i <= rows; i++) for(int j = 1; j <= i; j++) { if(j == 1) //每行的第一列的最大和 只能由上一行的第一列的最大和得到 result[i][j] = result[i - 1][j] + input[i][j]; else if(j == i) //每行的最后一列的最大和 只能由上一行的最后一列的最大和得到 result[i][j] = result[i - 1][j - 1] + input[i][j]; else //其他的则是可以由两个方向中大的那个得到 result[i][j] = Math.max(result[i - 1][j - 1], result[i - 1][j]) + input[i][j]; } } }