您的位置:首页 > 其它

acm pku 1050 To the Max的动态规划方法

2010-05-26 19:13 260 查看
TotheMax
Description
Givenatwo-dimensionalarrayofpositiveandnegativeintegers,asub-rectangleisanycontiguoussub-arrayofsize1*1orgreaterlocatedwithinthewholearray.Thesumofarectangleisthesumofalltheelementsinthatrectangle.Inthisproblemthesub-rectanglewiththelargestsumisreferredtoasthemaximalsub-rectangle.
Asanexample,themaximalsub-rectangleofthearray:

0-2-70
92-62
-41-41
-180-2
isinthelowerleftcorner:

92
-41
-18
andhasasumof15.
Input
TheinputconsistsofanN*Narrayofintegers.TheinputbeginswithasinglepositiveintegerNonalinebyitself,indicatingthesizeofthesquaretwo-dimensionalarray.ThisisfollowedbyN^2integersseparatedbywhitespace(spacesandnewlines).ThesearetheN^2integersofthearray,presentedinrow-majororder.Thatis,allnumbersinthefirstrow,lefttoright,thenallnumbersinthesecondrow,lefttoright,etc.Nmaybeaslargeas100.Thenumbersinthearraywillbeintherange[-127,127].
Output
Outputthesumofthemaximalsub-rectangle.
SampleInput
4

0-2-7092-62

-41-41-1


80-2

SampleOutput
15

Source
GreaterNewYork2001

这是求二维数组的最大子数组问题,其更为简单的形式是求一维数组的最大连续子段问题。现在还是从一维数组的最大子段问题谈起,对任意一个一维数组a
(共N个数),用b[j]表示a
中包括a[j]的前j个元素的最大连续子段的值。则必有:
b[j]=max{b[j-1]+a[j],a[j]},0≤j<N
这样一维数组的最大子段值,就是max{b[j]}0≤j<N。时间复杂度O(N)。
推广到二维,就是要想办法先将问题变为类似于一维的问题。其具体思想是:对二维数组的包含N行的列进行连续列划分,则共有N*N/2种,分别计算着N*N/2个矩阵的各列的和,则此时二维数组编成了一维数组,然后用一维数组求最大连续子段的方法可以求得需要的结果。时间复杂度O(N^3)。

具体实现如下:
#include"iostream"
usingnamespacestd;

constintN=100;
intitg

;

intMaxSum(intn,intitmp[])
{
inti,max,tmp;

max=itmp[0];
tmp=itmp[0];
for(i=1;i<n;i++)
{
//if(itmp>0)tmp+=itmp[i];//靠,垃圾,害得我WA3次,下次一定好好选择临时变量了。
if(tmp>0)tmp+=itmp[i];
elsetmp=itmp[i];
if(max<tmp)max=tmp;
}
returnmax;
}

intmain()
{
intn;
inti,j,k,max;
intitmp
,tmp;

cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>itg[i][j];
}
}

max=-200;
for(i=0;i<n;i++)
{
memset(itmp,0,sizeof(int)*N);
for(j=i;j<n;j++)
{
for(k=0;k<n;k++)itmp[k]+=itg[j][k];
tmp=MaxSum(n,itmp);
if(max<tmp)max=tmp;
}
}
cout<<max<<endl;

return0;
}
执行结果:

Problem:1050
User:uestcshe
Memory:252K
Time:16MS
Language:C++
Result:Accepted
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: