hdu-2084-number-tower-dp-java

Several towers

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 53741    Accepted Submission(s): 31567


Problem Description
When talking about the DP algorithm, a classic example is the number tower problem, which is described

as follows: There is a number tower as shown below, which requires going from the top to the bottom. If each step can only go to the adjacent node, What is the maximum sum of numbers of nodes passed through?

I already told you, this is a DP question, can you AC?
 

Input
The input data first includes an integer C, indicating the number of test instances, the first line of each test instance is an integer N (1 <= N <= 100), indicating the height of the tower, followed by N lines of numbers. A number tower, where the i-th row has i integers, and all integers are in the interval [0,99].
 

Output
For each test instance, output the maximum possible sum, one line per instance.
 

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

Sample Output
 
  
30
 

Source
2006/1/15 ACM programming final exam


problem- solving ideas:
                      I am curious, I wrote a recursive search and it really timed out (manually laughed and cried) and then honestly used dp to write emmm from the bottom to the top dp There is nothing to say about

import java.util.Scanner;

public class Main {

    private static int n;
    private static int[][] arr;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System .in);
        int t = scanner.nextInt();
        for (int i = 0; i < t; i++) {
            n = scanner.nextInt();
            arr = new int [n+1][n+1];
            int [][] dp = new int [n+1][n+1];
            for (int j = 1; j < arr.length-1; j++) {
                for (int j2 = 1; j2 <= j; j2++) {
                    arr[j][j2] = scanner.nextInt();
                }
            }
            for (int j = 1; j < dp.length; j++) {
                arr[n][j] = scanner.nextInt();
                dp[n][j] = arr[n][j];
            }
            for (int j = n-1; j >= 1; j--) {
                for (int j2 = 1; j2 <= j; j2++) {
                    dp[j][j2] = Math.max(dp[j+1][j2], dp[j+1][j2+1]) + arr[j][j2];
                }
            }
            System.out.println(dp[1][1]);
        }
    }

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324763367&siteId=291194637