Kadane's 1D algorithm O(N)
Kadane's algorithm /* maximum subarray a[k..l] of a[1..n] */
(k; l) := (0; 0); s := -inf; t := 0; j := 1;
for i:=1 to n do begin
t := t + a[i];
if t > s then begin (k; l) := (j; i); s := t end;
if t < 0 then begin t := 0; j := i + 1 end
end
int Kadane(int* A,int n,int* pk,int* pl)
{
*pk=0;
*pl=0;
int s=1<<31;
int t=0;
int i,j=0;
for(i=0;i {
t=t+A[i];
if(t>s)
{
*pk=j;
*pl=i;
s=t;
}
if(t<0)
{
t=0;
j=i+1;
}
}
return s;
}
Kadane's 2D algorithm O(N3)
#include
#include
using namespace std;
int main( void )
{
int N;
int t = 0;
int a[100][100];
int pr[100];
int S = 1<<31, s = 0, k, l, x1 = 0,x2 = 0,y1 = 0,y2 = 0,j;
cin >> N;
for( int i = 0; i < N; i++)
for( j = 0; j < N; j++)
cin >> a[i][j];
for( int z = 0; z < N; z++)
{
for(int i = 0; i < N; i++) pr[i] = 0;
for(int x = z; x < N; x++)
{
t = 0;
s = 1<<31;
j = 0;
k = 0; l = 0;
for(int i = 0; i < N; i++)
{
pr[i] = pr[i] + a[x][i];
t = t + pr[i];
if( t > s)
{
s = t;
k = i;
l = j;
}
if( t < 0 )
{
t = 0;
j = i + 1;
}
}
if( s > S)
{
S = s;
x1 = x;
y1 = k;
x2 = z;
y2 = l;
}
}
}
cout << x1 << " " << y1 << " " << x2 << " " << y2 << endl;
cout << S;
return 0;
}
阅读(863) | 评论(0) | 转发(0) |