复赛4:方格取数

洛谷:P7074

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**************************************************************** 
 * Description: 
 * Author: Alex Li
 * Date: 2023-10-20 13:42:17
 * LastEditTime: 2023-10-20 14:01:38
****************************************************************/
#include <iostream>
using namespace std;

int n,m;
int a[1010][1010];
long long f[1010][1010];
long long g[1010][1010];

int main(){
     cin>>n>>m;
     for (int i = 1; i <=n; i++){
        for (int j = 1; j <=m; j++){
            cin>>a[i][j];
        }
        
     }
     for (int  i = 0; i <=n+1; i++){
        for (int j = 0; j <=m+1; j++){
            f[i][j]=g[i][j]=-1e18;
        }
     }
     f[1][1]=a[1][1];
     for (int j = 1; j <=m; j++){
        for (int i = 0; i <=n; i++){
            f[i][j]=g[i][j]=max(f[i][j],f[i][j-1]+a[i][j]);
        }
       for(int i=1;i<=n;i++){
            f[i][j]=max(f[i][j],f[i-1][j]+a[i][j]);
       } 
       for (int i = n; i >=1;  i--){
             g[i][j]=max(g[i][j],g[i+1][j]+a[i][j]);
       }
       
       for (int i = 1; i <=n; i++){
        f[i][j]=max(f[i][j],g[i][j]);
       }
       

     }
     cout<<f[n][m]<<endl;
     
}
Scroll to Top