给定一个正整数n( n<=100),然后输入一个N*N矩阵。求矩阵中最大加权矩形,即矩阵的每一个元素都有一权值,权值定义在整数集上。从中找一矩形,矩形大小无限制,是其中包含的所有元素的和最大 。矩阵的每个元素属于[-127,127]
例:
0 –2 –7 0 在左下角: 9 2
9 2 –6 2 -4 1
-4 1 –4 1 -1 8
-1 8 0 –2 和为15
input:
第一行:n,接下来是n行n列的矩阵
output:
最大矩形(子矩阵)的和。
input:
4
0 –2 –7 0
9 2 –6 2
-4 1 -4 1
-1 8 0 –2
output:
15
【参考程序】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define findmax(xx,yy)(xx>yy?xx:yy)
int n,m,i,j,k,p,ans;
int a[210][210];
int main()
{
scanf("%d",&n);
memset(a,0,sizeof(a));
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
a[i][j]+=a[i-1][j]+a[i][j-1]-a[i-1][j-1];
}
ans=-0xfffffff;
for (k=1;k<=n;k++)
for (p=1;p<=n;p++)
for (i=1;i<=n-k+1;i++)
for (j=1;j<=n-p+1;j++)
ans=findmax(ans,a[i+k-1][j+p-1]-a[i+k-1][j-1]-a[i-1][j+p-1]+a[i-1][j-1]);
printf("%d\n",ans);
system("pause");
return 0;
}
--------------------另外的代码,与此题无关,只是相似-------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int n,m,i,j,t,ans,k;
int a[300][300];
int main()
{
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
for (i=1;i<=n;i++)
for (j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
a[i][j]+=a[i][j-1];
}
ans=-0xfffffff;
for (i=1;i<=m;i++)
for (j=i;j<=m;j++)
{
t=a[1][j]-a[1][i-1];
if (t>ans) ans=t;
for (k=2;k<=n;k++)
if (t>0) t+=a[k][j]-a[k][i-1];
else t=a[k][j]-a[k][i-1];
if (t>ans) ans=t;
}
printf("%d\n",ans);
system("pause");
return 0;
}
-----------------------------pascal------------------------------------------
var n,m,i,j,k,t,ans:longint;
s:array[0..300,0..300]of longint;
begin
read(n,m);
for i:=1 to n do
for j:=1 to m do begin
read(s[i,j]);
inc(s[i,j],s[i,j-1]);
end;
ans:=-32767;
for i:=1 to m do
for j:=i to m do begin
t:=s[1,j]-s[1,i-1];
if t>ans then ans:=t;
for k:=2 to n do begin
if t>0 then
inc(t,s[k,j]-s[k,i-1])
else t:=s[k,j]-s[k,i-1];
if t>ans then ans:=t;
end;
end;
writeln(ans);
end.