동적 계획 – 최대 하위 섹션 및

#include <stdio.h>

int MaxSum(int n, int *a, int *besti, int *bestj)
{
	int sum = 0, i,j,k, thissum;
	for(i = 0; i < n; i++)
	{
		for(j=0; j < n; j++)
		{
			thissum = 0;
			for(k = i; k <= j; k++) thissum += a[k];
			if(thissum > sum)
			{
				sum = thissum;
				*besti = i;
				*bestj = j;
			}			
		}
	}
	return sum;
}

int MaxSum_2(int n, int *a, int *besti, int *bestj)
{
	int sum = 0, i, j, thissum;
	for(i = 0; i < n; i++)
	{
		thissum = 0;
		for(j = i; j < n; j++)
		{
			thissum += a[j];
			if(thissum > sum)
			{
				sum = thissum;
				*besti = i;
				*bestj = j;
			}
		}
	}
	return sum;
}

int MaxSubSum(int *a, int left, int right)
{
	int sum = 0, center, leftSum, rightSum;
	int i, lefs = 0, s1 = 0, rights = 0, s2 = 0;
	if(left==right) sum=a[left] >0?a[left]:0;
	else{
		center = (left+right)/2;
		leftSum = MaxSubSum(a, left, center);
		rightSum = MaxSubSum(a, center+1, right);
		for(i = center; i>=left; i--)
		{
			lefs += a[i];
			if(lefs>s1) s1 = lefs;	
		}
		for(i = center+1; i<=right; i++)
		{
			rights += a[i];
			if(rights > s2) s2 = rights;
		}
		sum = s1+s2;
		if(sum < leftSum) sum = leftSum;
		if(sum < rightSum) sum = rightSum;		
	}
	return sum;
}

int MaxSum_3(int n,int *a)
{
	return MaxSubSum(a,0, n-1);
}

int MaxSum_4(int n, int *a)
{
	int sum = 0, b = 0 ,i;
	for(i = 0; i < n; i++)
	{
		if(b > 0) b+=a[i];
		else b = a[i];
		if(b > sum) sum = b;
	}
	return sum;
}

int main()
{
	int a[]={-2,11,-4,13,-5,-2};
	int left, right, sum;
	//sum = MaxSum(6, a, &left, &right);printf("MaxSum = %d, left = %d, right = %d
",sum,left, right); //sum = MaxSum_2(6, a, &left, &right);printf("MaxSum = %d, left = %d, right = %d
",sum,left, right); //sum = MaxSum_3(6,a);printf("MaxSum = %d
",sum); sum = MaxSum_4(6,a);printf("MaxSum = %d
",sum); system("pause"); return 0; }

좋은 웹페이지 즐겨찾기