最大和和矩阵是最大和子段的推广,是最大和子段推广到二维的形式,当然我们可把二维形再转化成一维的形式,这就是求最大和矩阵方法了!二维转化为一维时我们直接用穷举法!
代码如下:
#include<stdio.h>
int MaxSum(int n,int *a)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int sum=0,b=0;
for(int i=1;i<=n;i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(b>0)
b+=a[i];
else
b=a[i];
if(b>sum) sum=b;
}
return sum;
}
int MaxSum2(int m,int n,int a[][100])
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int sum=0;
int *b=new int [n+1];
for(int i=1;i<=m;i++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for(int k=1;k<=n;k++)
b[k]=0;
![](http://www.cppblog.com/Images/OutliningIndicators/InBlock.gif)
for(int j=i;j<=m;j++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for(int k=1;k<=n;k++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
b[k]+=a[j][k];
int max=MaxSum(n,b);
if(max>sum)
sum=max;
}
}
}
delete b;
return sum;
}
int main()
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](http://www.cppblog.com/Images/OutliningIndicators/ContractedBlock.gif)
{
int a[100][100],i,j,n,sum,m;
while(scanf("%d %d",&m,&n)!=EOF)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
scanf("%d",&a[i][j]);
}
sum=MaxSum2(m,n,a);
printf("%d\n",sum);
}
return 0;
}
运行结果如下:
posted on 2010-09-10 13:09
jince 阅读(511)
评论(0) 编辑 收藏 引用 所属分类:
算法设计与分析