求最大子长方体的价值和。。。
大复杂度水过。。。。
代码如下:
注意: 读入数据的时候请用long long 读入,
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <time.h>
#include <cstdlib>
#define M 25
#define mod 1000000007
#define eps 1e-7
#define INF 0x7fffffff
#define LL long long
using namespace std;
LL st[M][M][M];
int A, B, C;
LL sum(int x1, int x2, int y1, int y2, int z)
{
LL ans = 0;
for(int i = x1; i <= x2; ++i)
for(int j = y1; j <= y2; ++j)
ans += st[i][j][z];
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d%d", &A, &B, &C);
for(int i = 0; i < A; ++i)
for(int j = 0; j < B; ++j)
for(int k = 0; k < C; ++k)
scanf("%lld", &st[i][j][k]);
LL ans = -(1LL<<60);
for(int x1 = 0; x1 < A; ++x1)
for(int x2 = x1; x2 < A; ++x2)
for(int y1 = 0; y1 < B; ++y1)
for(int y2 = y1; y2 < B; ++y2)
{
LL d[M];
for(int i = 0; i < C; ++i)
d[i] = sum(x1,x2,y1,y2,i);
LL maxx = -(1LL<<60), s = 0;
for(int i = 0; i < C; ++i)
{
if(s<0) s = 0;
s += d[i];
maxx = max(maxx, s);
}
ans = max(ans, maxx);
}
printf("%lld\n", ans);
if(t) printf("\n");
}
return 0;
}
高效代码(O(n^5))预处理一下(用空间换时间)
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <time.h>
#include <cstdlib>
#define M 25
#define mod 1000000007
#define eps 1e-7
#define INF 0x7fffffff
#define LL long long
using namespace std;
LL st[M][M][M], s[M][M][M];
int A, B, C;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
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", &st[i][j][k]);
for(int k = 1; k <= C; ++k)
for(int i = 1; i <= A; ++i)
for(int j = 1; j <= B; ++j)
s[i][j][k] = st[i][j][k] + s[i-1][j][k] + s[i][j-1][k] - s[i-1][j-1][k];
LL ans = -(1LL<<60);
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)
{
LL d[M];
for(int i = 1; i <= C; ++i)
d[i] = s[x2][y2][i]-s[x1-1][y2][i]-s[x2][y1-1][i]+s[x1-1][y1-1][i];
LL maxx = -(1LL<<60), s = 0;
for(int i = 1; i <= C; ++i)
{
if(s<0) s = 0;
s += d[i];
maxx = max(maxx, s);
}
ans = max(ans, maxx);
}
printf("%lld\n", ans);
if(t) printf("\n");
}
return 0;
}