i, j 代表列
用前缀和预处理出i,j之间的和
枚举i,j 那么i到j之间的和就相当于最长连续字段和的一位,对n行都做相同处理,再做一遍最长连续字段和即可。
最长连续字段和的 dp方程 dp[i] = max(dp[i-1] + a[i], a[i]);
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5 int n, a[110][110], sum[110][110], tmp[110], dp[110], ans; 6 int main() 7 { 8 scanf("%d", &n); 9 for (int i = 1; i <= n; i++) 10 for (int j = 1; j <= n; j++) 11 scanf("%d", &a[i][j]); 12 for (int i = 1; i <= n; i++) 13 for (int j = 1; j <= n; j++) 14 sum[i][j] += sum[i][j-1] + a[i][j]; 15 for (int i = 1; i <= n; i++) 16 for (int j = i; j <= n; j++){ 17 memset(dp, 0, sizeof(dp)); 18 for (int k = 1; k <= n; k++) 19 { 20 tmp[k] = sum[k][j] - sum[k][i-1]; 21 } 22 for(int l = 1; l <= n; l++) 23 { 24 dp[l] = max(dp[l-1] + tmp[l], tmp[l]); 25 if(dp[l] > ans)ans = dp[l]; 26 } 27 } 28 printf("%d ", ans); 29 }