首页 > 其他 > 详细

最大子列和问题

时间:2015-11-30 23:59:59      阅读:491      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
int MaxSubseqSum1(int A[], int N);
int MaxSubseqSum2(int A[], int N);
int MaxSubseqSum3(int A[], int N); 
int Max3(int A, int B, int C);
int DevideAndConquer(int A[], int left, int right); 
int main()
{
	int MaxSum;
	int A[100000];
	int N;
	int i;
	scanf("%d", &N);
	for(i=0; i<N; i++)
	{
		scanf("%d", &A[i]);
	}
	MaxSum = MaxSubseqSum3(A, N);
	printf("%d\n", MaxSum);
	return 0;
}

int MaxSubseqSum1(int A[], int N)
{
	int ThisSum, MaxSum=0;
	int i, j, k;
	for(i=0; i<N; i++)
	{
		for(j=i; j<N; j++)
		{
			ThisSum = 0;
			for(k=i; k<=j; k++)
			{
				ThisSum += A[k];
			}
			if(ThisSum > MaxSum)
			{
				MaxSum = ThisSum;
			}
		}
	}
	return MaxSum;
}
int MaxSubseqSum2(int A[], int N)
{
	int ThisSum, MaxSum=0;
	int i, j, k;
	for(i=0; i<N; i++)
	{
		ThisSum = 0;
		for(j=i; j<N; j++)
		{
			ThisSum += A[j];
			if(ThisSum > MaxSum)
			{
				MaxSum = ThisSum;
			}
		}
	}
	return MaxSum;
}
int DevideAndConquer(int A[], int left, int right)
{
	if(left == right)
	{
		if(A[left] > 0)
		{
			return A[left];
		}
		else
		{
			return 0;
		}
	}
	int MaxLeft=0, MaxRight=0, MaxLeftBorderSum=0, MaxRightBorderSum=0, LeftBorderSum=0, RightBorderSum=0;
	int i=0;
	int center = (left+right) / 2;
	MaxLeft = DevideAndConquer(A, left, center);
	MaxRight = DevideAndConquer(A, center+1, right);
	
	for(i=center; i>=left; i--)
	{
		LeftBorderSum += A[i];
		if(LeftBorderSum > MaxLeftBorderSum)
		{
			MaxLeftBorderSum = LeftBorderSum;
		}
	}
	
	for(i=center+1; i<=right; i++)
	{
		RightBorderSum += A[i];
		if(RightBorderSum > MaxRightBorderSum)
		{
			MaxRightBorderSum = RightBorderSum;
		}
	}
	
	return Max3(MaxLeft, MaxRight, MaxLeftBorderSum+MaxRightBorderSum);
}
int MaxSubseqSum3(int A[], int N)
{
	DevideAndConquer(A, 0, N-1);
}
int Max3(int A, int B, int C)
{
	return A>B ? A>C?A:C : B>C?B:C;
}

  

最大子列和问题

原文:http://www.cnblogs.com/guyueyue/p/5008583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!