DP Model Digital Triangle Picking Peanuts

Related topics

Digital triangle

Minimum toll

Grid access

Title description :
Hello Kitty would like to pick some peanuts and give it to her favorite Mi
Mouse. She came to a rectangular peanut field with grid-like roads and went in from the northwest corner and came out from the southeast corner.Insert picture description here

There is a peanut seedling planted at the intersection of each road in the field, with several peanuts on it, and all the peanuts on it can be picked after one peanut seedling.

Hello Kitty can only go east or south, not west or north. Ask Hello Kitty how many peanuts can be picked at most.

Input format

The first line is an integer T, which represents how many sets of data there are.

Next is the T group data. The first row of each group of data is two integers, representing the row number R and the column number C of peanut seedlings.

The next R rows of data of each group of data describe the situation of each row of peanut seedlings from north to south. Each row of data has C integers, describing the number of peanuts M on each peanut seedling in the row in order from west to east.

Output format

For each set of input data, output one line, the content is the maximum number of peanuts that Hello Kitty can pick.

data range

1≤T≤100,
1≤R,C≤100,
0≤M≤1000

Input sample:

2
2 2
1 1
3 4
2 3
2 3 4
1 6 5

Sample output:

8
16

Ideas

1.这题跟数字三角形一样根据题意我们先设一
个二维状态方程dp[i][j]表示Kitty偷到第i行
第j列时的最大值

2.只能从只能向东或向南走,因此状态转移方
程dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1])+arr[i][j];

Code

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input=new Scanner(System.in);
        int T=input.nextInt();
        for(int i=0;i<T;i++){
    
    
            int R=input.nextInt();
            int C=input.nextInt();
            int arr[][]=new int[R+1][C+1];
            int dp[][]=new int[R+1][C+1];
            for(int m=1;m<=R;m++){
    
    
                for(int n=1;n<=C;n++){
    
    
                    arr[m][n]=input.nextInt();
                }
            }

            for(int m=1;m<=R;m++){
    
    
                for(int n=1;n<=C;n++){
    
    
                    dp[m][n]=Math.max(dp[m-1][n],dp[m][n-1])+arr[m][n];
                }
            }
            System.out.println(dp[R][C]);
        }
        
    }
}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/108331027