UVA - 10755 Garbage Heap

Input
The first line of the input contains the number of the test cases, which is at most 15. The descriptions
of the test cases follow. The first line of a test case description contains three integers A, B, and C
(1 ≤ A, B, C ≤ 20). The next lines contain A · B · C numbers, which are the values of garbage pieces.
Each number does not exceed 2 31 by absolute value. If we introduce coordinates in the parallelepiped
such that the cell in one corner is (1,1,1) and the cell in the opposite corner is (A, B, C), then the values
are listed in the order
(1, 1, 1), (1, 1, 2), . . . , (1, 1, C),
(1, 2, 1), . . . , (1, 2, C), . . . , (1, B, C),
(2, 1, 1), . . . , (2, B, C), . . . , (A, B, C).
The test cases are separated by blank lines.
Output
For each test case in the input, output a single integer denoting the maximal value of the new garbage
heap. Print a blank line between test cases.
Sample Input
1
2 2 2
-1 2 0 -3 -2 -1 1 5
Sample Output
6

 

对每一层(z方向)求二维前缀和,再枚举x,y的上下边界,总共是O(n)的复杂度

#include <cstdio>
#include <algorithm>
#include <iostream>

#define N 25
#define ll long long

ll A[N][N][N], T, a, b, c, INF = -1ll << 60, S = INF, s, k;

long long int sum(int x1, int x2, int y1, int y2, int z);

using namespace std;

int main() {
    cin >> T;
    while (T--) {
        cin >> a >> b >> c, S = INF;
        for (int x = 1; x <= a; ++x) {
            for (int y = 1; y <= b; ++y) {
                for (int z = 1; z <= c; ++z) {
                    cin >> A[x][y][z];
                    A[x][y][z] += A[x - 1][y][z] + A[x][y - 1][z] - A[x - 1][y - 1][z];
                }
            }
        }
        for (int x1 = 1; x1 <= a; ++x1) {
            for (int x2 = x1; x2 <= a; ++x2) {
                for (int y1 = 1; y1 <= b; ++y1) {
                    for (int y2 = y1; y2 <= b; ++y2) {
                        s = INF, k = 0;
                        for (int z = 1; z <= c; ++z) {
                            ll t = sum(x1, x2, y1, y2, z); //转化为求最大和的连续子序列
                            k += t;
                            if (k >= 0) {
                                s = max(k , s);
                            } else {
                                k = 0;
                                s = max(t, s);
                            }
                        }
                        S = max(S, s);
                    }
                }
            }
        }
        cout << S << endl;
        if (T)
            cout << endl;
    }
}

ll sum(int x1, int x2, int y1, int y2, int z) {
    return A[x2][y2][z] - A[x1 - 1][y2][z] - A[x2][y1 - 1][z] + A[x1 - 1][y1 - 1][z];
}

 

posted @ 2017-10-29 22:01  少年啦飞驰  阅读(172)  评论(0编辑  收藏  举报