首页 > 代码库 > 【UVA】108 - Maximum Sum(DP矩阵)

【UVA】108 - Maximum Sum(DP矩阵)

n^3的复杂度计算最小子矩阵,用了最大连续和的DP算法。

14273282108Maximum SumAcceptedC++0.0132014-09-27 

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 1 << 30;
const int maxn = 127 + 3;
int mat[maxn][maxn];
int main(){
    int n;
    while(scanf("%d",&n) != EOF){
        memset(mat,0,sizeof(mat));
        for(int i = 1 ; i <= n ; i ++)
            for(int j = 1 ; j <= n ; j++){
                int value;
                scanf("%d",&value);
                mat[i][j] = mat[i][j - 1] + value;
            }
        int ans = -INF;
        for(int k = 1 ; k <= n ; k++){
            for(int j = 0 ; j < k ; j++){
                int sum = mat[1][k] - mat[1][j];
                for(int i = 2; i <= n ; i++){
                     sum = max(mat[i][k] - mat[i][j],sum + (mat[i][k] - mat[i][j]));
                     ans = max(sum,ans);
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

【UVA】108 - Maximum Sum(DP矩阵)