EIUGAME - Maximum path sum

Xem dạng PDF

Gửi bài giải

Điểm: 1,00 (OI)
Giới hạn thời gian: 1.0s
Giới hạn bộ nhớ: 256M
Input: stdin
Output: stdout

Nguồn bài:
Hà Minh Ngọc
Dạng bài
Ngôn ngữ cho phép
C, C++, Java, Kotlin, Pascal, PyPy, Python, Scratch

Given a matrix of ~n~ rows and ~m~ columns numbered from top to bottom, left to right, each cell in the matrix is a random number whose absolute value does not exceed ~10^9~. From the upper left position, find a path to the lower right corner position so that the number of squares to go through is minimal (each move only goes to the square with a common edge). Among those ways, find a way to maximize the sum of the values of the cells on the path.

Input

  • The first line is ~2~ integers ~n~, ~m~ (~n~, ~m \leq 2\times10^3~).
  • The ~i^{th}~ line of the next ~n~ lines contains ~m~ space-separated integers. The ~j^{th}~ value in line ~i~ corresponds to the ~a_{i,j}~ value in the matrix(~|a_{i,j}| \leq 10^9~).

Output

  • A single integer that is the maximum sum along the path found.

Example Input 1

3 3
1 2 3
-1 5 6
0 2 9

Example Output 1

23

Bình luận

Hãy đọc nội quy trước khi bình luận.



  • 0
    eiuphattan2231200138  đã bình luận lúc 10, Tháng 11, 2026, 1:57 ← sửa 6

    fix comment error line

     long[][] matrix = new long[n+1][m+1];
       0  1  2  3
     0 0  0  0  0
     1 0  1  2  3
     2 0  -1 5  6 
     3 0  0  2  9
    
     long[][] dp = new long[n+1][m+1];
     for(i=1 < n+1){
        for(j=1 < m+1){
           dp[i][j] = matrix[i][j] + Math.max(dp[i-1][j], dp[i][j-1]);
        } 
     }
       0  1  2  3
     0 0  0  0  0
     1 0  1  3  6
     2 0  0  8  14 
     3 0  0  10  23
    
     max = dp[n][m] = 23
    
     lưu ý: dp[][] gán giá trị dòng thứ 0, cột thứ 0 với long.MIN_VALUE thay vì dùng số 0 để không ảnh hưởng tính toán. Chừa 1 chỗ bằng 0 (dp[0][1] = 0 )