二维的最大字段和算法:
#include <iostream>
#include <cstring>
using namespace std;
#define MIN -1000000;
#define MAXSIZE 1001//注意边界条件,根据具体问题,更改MAXSIZE
int num[MAXSIZE][ MAXSIZE];
struct Point
{
intx,y;
}start,end;
int maxsum1(int *num, int len, int &s,int &e)// 一维的最大字段和
{
inti, b = 0;
intstart = 1, end = 0;
intsum = MIN;
for( i = 0; i < len; i++) {
if (b >= 0) {
b += num[i];
end++;
} else {
b = num[i];
start = i;
end = i;
}
if (b > sum) {
sum = b;
s = start;
e = end;
}
}
return sum;
}
int maxsum2(int num[][MAXSIZE], int n ,int m,Point &start,Point &end)//n行m列,start
{ //中保存的起始的x,y坐标,end保存的结束的x,y的坐标
int i , j , k;
int sum = -0x7FFFFFFF;
int b[MX];
for(i=0 ; i<n ; i++)
{
memset(b , 0 , sizeof(b));
for(j=i ; j<m ; j++)
{
for(k=0 ; k<m ; k++)b[k] += num[j][k];
int s,e;
int max = maxsum1(b, m,s,e);
if(max > sum)
{
sum = max;
start.x=i;start.y=s-1;
end.x=j;end.y=e-1;
}
}
}
return sum;
}