UVA - 10755 Garbage Heap
Farmer John has a heap of garbage formed in a rectangular parallelepiped. It consists of A×B ×C garbage pieces each of which has a value. The value of a piece may be 0, if the piece is neither profitable nor harmful, and may be negative which means that the piece is not just unprofitable, but even harmful (for environment). The farmer thinks that he has too much harmful garbage, so he wants to decrease the heap size, leaving a rectangular nonempty parallelepiped of smaller size cut of the original heap to maximize the sum of the values of the garbage pieces in it. You have to find the optimal parallelepiped value. (Actually, if all smaller parallelepiped has value less than the original one, the farmer will leave the original parallelepiped).
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 231 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
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.
题解:
多维问题降维,我们在长方体上n^4枚举一个矩形,每次统计的子长方体的一个面都是这样的大小,把这个面的权值算出来,然后On枚举第三维,这样就转化成了序列上最长连续子段和问题了。
代码:
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <iostream> #define MAXN 25 #define inf (1e17) #define ll long long using namespace std; ll sum[MAXN][MAXN][MAXN],w[MAXN][MAXN][MAXN]; int a,b,c; ll rezero(int h,int hh,int i,int j,int k){ return sum[i][j][k]-sum[h-1][j][k]-sum[i][hh-1][k]+sum[h-1][hh-1][k]; } void work(){ memset(sum,0,sizeof(sum)); memset(w,0,sizeof(w)); scanf("%d%d%d",&a,&b,&c); for(int i=1;i<=a;i++) for(int j=1;j<=b;j++) for(int k=1;k<=c;k++){ scanf("%lld",&w[i][j][k]); } for(int k=1;k<=c;k++) for(int i=1;i<=a;i++) for(int j=1;j<=b;j++){ sum[i][j][k]=sum[i-1][j][k]+sum[i][j-1][k]-sum[i-1][j-1][k]+w[i][j][k]; } ll ans=-inf; for(int i=1;i<=a;i++) for(int j=1;j<=b;j++) for(int h=1;h<=i;h++) for(int hh=1;hh<=j;hh++){ ll sm=-inf; for(int k=1;k<=c;k++){ sm=max(rezero(h,hh,i,j,k),rezero(h,hh,i,j,k)+sm); ans=max(ans,sm); } } printf("%lld\n",ans); } int main() { int t;scanf("%d",&t); while(t--){ work(); if(t) printf("\n"); } return 0; }