Blue Bridge Cup official website practice questions (digital triangle)

Question description

image description

The image above gives a digital triangle. There are many different paths from the top to the bottom of the triangle. For each path, add up the numbers on the path to get a sum. Your task is to find the largest sum.

Each step on the path can only go from one number to the next level and its closest left or right number. In addition, the number of times walking down to the left and the number of times walking down to the right cannot differ by more than 1.

Enter description

The first line of input contains an integer N (1≤N≤100), representing the number of rows of the triangle.

The N rows below give the numerical triangle. The numbers on the digital triangle are all integers between 0 and 100.

Output description

Output an integer representing the answer.

Input and output samples

Example

enter

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

output

27

operating restrictions

  • Maximum running time: 1s
  • Maximum running memory: 256M
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n=scan.nextInt();
        int[][] a=new int[n+1][n+1];
        for(int i=1;i<=n;i++){
          for(int j=1;j<=i;j++){
            a[i][j]=scan.nextInt();
            a[i][j]=a[i][j]+Math.max(a[i-1][j-1],a[i-1][j]);
          }
        }
        if(n%2==0){
          System.out.println(Math.max(a[n][n/2],a[n][n/2+1]));
        }
        else{
          System.out.println(a[n][n/2+1]);
        }
        scan.close();
    }
}

Guess you like

Origin blog.csdn.net/s44Sc21/article/details/132779887