天天看點

POJ 1050 To the Max(字首和)

POJ 1050 To the Max(字首和)

題意:給出一個n x n矩陣、找出一個子矩陣、使其和最大

source:http://poj.org/problem?id=1050

solution:用字首和的思路可以很好的求解

#include <bits/stdc++.h>
using namespace std;
const int maxn = 101;
const int INF = 0x3f3f3f3f;
int n, a[maxn][maxn], f[maxn][maxn], ans = -INF;     //f[i][j]關于第j列到第i行的列字首和
int b[maxn], sum[maxn]; //降維後的數組
int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            scanf("%d", &a[i][j]);
    for(int i = 1; i <= n; ++i)
         for(int j = 1; j <= n; ++j)
             f[i][j] = f[i - 1][j] + a[i][j];
    for(int i = 1; i <= n; ++i)
        for(int j = i; j <= n; ++j)
        {
            for(int k = 1; k <= n; ++k) b[k] = f[j][k] - f[i - 1][k];    //降維
            for(int k = 1; k <= n; ++k) sum[k] = sum[k - 1] + b[k];        //求一維字首和
            int Min = INF;
            for(int k = 1; k <= n; ++k)
            {
                Min = min(Min, sum[k - 1]);
                ans = max(ans, sum[k] - Min);
            }
        }
    printf("%d\n", ans);
    return 0;
}