Farmer John has a heap of garbage formed in a rectangular paral-
lelepiped. 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 pro
table nor harmful, and may be negative which means that the piece is
not just unpro table, 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 nd 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 rst line of the input contains the number
of the test cases, which is at most 15. The descriptions of the test
cases follow. The rst 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.
如果只有一维的话,贪心就可以了,复杂度O(n)。
如果有两维的话,预处理前缀和,枚举其中一维的上下边界,就转化成了一维问题,复杂度O(n^3)。
如果有三维的话,只需要枚举其中两维,复杂度O(n^5)。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
const LL oo=1e16;
LL a[25][25][25],s[25][25][25];
int m,n,p;
LL get(int i1,int j1,int k1,int i2,int j2,int k2)
{
return s[i2][j2][k2]
-s[i1-1][j2][k2]-s[i2][j1-1][k2]-s[i2][j2][k1-1]
+s[i1-1][j1-1][k2]+s[i1-1][j2][k1-1]+s[i2][j1-1][k1-1]
-s[i1-1][j1-1][k1-1];
}
void init()
{
int i,j,k;
scanf("%d%d%d",&m,&n,&p);
for (i=1;i<=m;i++)
for (j=1;j<=n;j++)
for (k=1;k<=p;k++)
{
scanf("%lld",&a[i][j][k]);
s[i][j][k]=s[i-1][j][k]+s[i][j-1][k]+s[i][j][k-1]
-s[i-1][j-1][k]-s[i-1][j][k-1]-s[i][j-1][k-1]
+s[i-1][j-1][k-1]+a[i][j][k];
}
}
LL solve()
{
int i1,i2,j1,j2,k;
LL ans=-oo,x,now;
for (i1=1;i1<=m;i1++)
for (i2=1;i2<=i1;i2++)
for (j1=1;j1<=n;j1++)
for (j2=1;j2<=j1;j2++)
{
now=0;
for (k=1;k<=p;k++)
{
x=get(i2,j2,k,i1,j1,k);
now+=x;
ans=max(ans,now);
now=max(0LL,now);
}
}
return ans;
}
int main()
{
int T,K;
scanf("%d",&T);
for (K=1;K<=T;K++)
{
init();
printf("%lld\n",solve());
if (K<T) printf("\n");
}
}