最大子矩阵
Problem Description
给你一个m×n的整数矩阵,在上面找一个x×y的子矩阵,使子矩阵中所有元素的和最大。
Input
输入数据的第一行为一个正整数T,表示有T组测试数据。每一组测试数据的第一行为四个正整数m,n,x,y(0 <m,n<1000 AND 0 <x<=m AND 0 <y<=n),表示给定的矩形有m行n列。接下来这个矩阵,有m行,每行有n个不大于1000 的正整数。
Output
对于每组数据,输出一个整数,表示子矩阵的最大和。
Sample Input
1
4 5 2 2
3 361 649 676 588
992 762 156 993 169
662 34 638 89 543
525 165 254 809 280
Sample Output
2474
Author
lwg
Source
HDU 2006 -12 Programming Contest
Recommend
LL | We have carefully selected several similar problems for you: 1081 1003 1505 1257 1024
二维树状数组处理,然后暴力查找。
当做二维树状数组点的练手题做了。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
#include<string>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#include<set>
#include<map>
#include<cstdio>
#include<limits.h>
#define fir first
#define sec second
#define fin freopen("/home/ostreambaba/文档/input.txt", "r", stdin)
#define fout freopen("/home/ostreambaba/文档/output.txt", "w", stdout)
#define mes(x, m) memset(x, m, sizeof(x))
#define pii pair<int, int>
#define Pll pair<ll, ll>
#define INF 1e9+7
#define Pi 4.0*atan(1.0)
#define MOD 1000000007
#define lowbit(x) (x&(-x))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ls rt<<1
#define rs rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-12 ;
const int maxn = 1010 ;
using namespace std ;
inline int read(){
int x(0 ),f(1 );
char ch=getchar();
while (ch<'0' ||ch>'9' ) {if (ch=='-' ) f=-1 ;ch=getchar();}
while (ch>='0' &&ch<='9' ) x=x*10 +ch-'0' ,ch=getchar();
return x*f;
}
int N, M;
int mat[maxn][maxn];
inline void update(int x,int y,int cnt)
{
for (int i=x; i<=N; i+=lowbit(i)){
for (int j=y; j<=M; j+=lowbit(j)){
mat[i][j]+=cnt;
}
}
}
inline int getSum(int x,int y)
{
int res=0 ;
for (int i=x; i>0 ; i-=lowbit(i)){
for (int j=y; j>0 ; j-=lowbit(j)){
res+=mat[i][j];
}
}
return res;
}
int main()
{
int x,y,num;
int Case;
Case=read();
while (Case--){
mes(mat, 0 );
M=read();
N=read();
x=read();
y=read();
for (int i=1 ; i<=M; ++i){
for (int j=1 ; j<=N; ++j){
num=read();
update(i,j,num);
}
}
int res=-INF;
int sum;
for (int i=1 ; i+x-1 <=N; ++i){
for (int j=1 ; j+y-1 <=M; ++j){
sum=getSum(i+x-1 ,j+y-1 )+getSum(i-1 ,j-1 )-getSum(i+x-1 ,j-1 )-getSum(i-1 ,j+y-1 );
res=max(res,sum);
}
}
printf ("%d\n" ,res);
}
return 0 ;
}