UVA10755 Garbage Heap 三维子矩阵最大和

题意:三维子矩阵最大和。

解法:枚举三维的平面两维,然后将第三维转化为线性求解,时间复杂度O(n^5),这题被读入数据方位坑了,绝对值不超过2^31,负数没有问题,int形最大正整数是2^31-1......  导致一直WA,欲哭无泪。

代码如下:

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;

const LL INF = 1LL<<60;
int A, B, C;
LL sumz[25][25][25]; // 平面上[1,1]到[i][j]在高度为k时的区域前缀和

LL get(int x1, int y1, int x2, int y2, int z) {
    return sumz[x2][y2][z] - sumz[x1-1][y2][z] - sumz[x2][y1-1][z] + sumz[x1-1][y1-1][z];
}

void solve() {
    // 需要枚举平面上的二维组合
    LL ret = -INF;
    LL Min, s;
    for (int i = 1; i <= A; ++i) {
        for (int j = i; j <= A; ++j) {
            for (int k = 1; k <= B; ++k) {
                for (int h = k; h <= B; ++h) {
                    Min = 0;
                    for (int p = 1; p <= C; ++p) {
                        s = get(i, k, j, h, p);
                        ret = max(ret, s - Min);
                        if (s < Min) Min = s;
                    }
                }
            }
        }
    }
    printf("%lld\n", ret);
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d %d %d", &A, &B, &C);
        LL tot, x;
        for (int i = 1; i <= A; ++i) {
            for (int j = 1; j <= B; ++j) {
                tot = 0;
                for (int k = 1; k <= C; ++k) {
                    scanf("%lld", &x);
                    tot += x;
                    sumz[i][j][k] = sumz[i-1][j][k] + sumz[i][j-1][k] - sumz[i-1][j-1][k] + tot;
                }
            }
        }
        solve();
        if (T) puts("");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Lyush/p/3110121.html