洛谷P1719(最大子矩阵)

https://www.luogu.org/problem/P1719
用前缀和处理每一列从第一行加到它的值,然后问题转化为最大子序列和,时间复杂度:

#include
#include
using namespace std;
int a[125][125];
int s[125][125];
int res;
int sum;
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> a[i][j];
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            s[i][j] = s[i - 1][j] + a[i][j];
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
            sum = 0;
            for (int k = 1; k <= n; k++) {
                sum += s[j][k] - s[i][k];
                res = max(res, sum);
                if (sum < 0) sum = 0;
            }
        }
    }
    cout << res;
}

你可能感兴趣的:(洛谷P1719(最大子矩阵))