【算法】最大子序列的四种算法

#include<iostream>
#include<ctime>

using namespace std;
int Max_3(int a, int b, int c)  //3个数中大
{
	if (a > b)
	{
		if (a > c)
			return a;
		else
			return c;
	}
	else
	{
		if (b > c)
			return b;
		else
			return c;
	}
}

int MaxSum_1(const int a[], int n)  //穷举法
{
	int maxsum=0, thissum,j,k;
	for (int 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 MaxSum_2(const int a[], int n)  //穷举法改进
{
	int maxsum = 0, thissum, j;
	for (int i = 0; i < n; i++)
	{
		thissum = 0;
		for (j = i; j < n; j++)
		{
			thissum += a[j];
			if (thissum > maxsum)
				maxsum = thissum;
		}
	}
	return maxsum;
}
int MaxSum_3(const int a[], int n)  //联机算法
{
	int maxsum = 0, thissum = 0,i;
	for (int i = 0; i < n; i++)
	{	thissum += a[i];
		if (thissum > maxsum)
			maxsum = thissum;
		else if (thissum < 0)
			thissum = 0;
	}
	return maxsum;
}

int MaxSum_4(int a[],int left,int right)  // 分治算法,递归
{
	int leftmax, rightmax;  //左边和右边的最大数
	int leftbordermax, rightbordermax;  //左右边界的最大数
	int leftborde, rightborde;         //边界左右的值
	int center,i;

	if (left == right)                //基准情形
		if(a[left]>0)
			return a[left];
		else
			return 0;

	center = (left + right) / 2;
	leftmax = MaxSum_4(a, left, center);
	rightmax = MaxSum_4(a, center+1, right);

	leftbordermax = leftborde = 0;    //左边界的最大值
	for (i = center; i >= left; i--)
	{
		leftborde += a[i];
		if (leftborde > leftbordermax)
			leftbordermax = leftborde;
	}

	rightbordermax = rightborde = 0;  //右边界的最大值
	for (i = center+1; i <= right; i++)
	{
		rightborde += a[i];
		if (rightborde > rightbordermax)
			rightbordermax = rightborde;
	}
	return Max_3(leftmax, leftbordermax + rightbordermax, rightmax);
}

int main()
{
	int max_sum, s[10000];
	for (int i = 0; i < 10000; i += 3)
	{
		s[i] = 1;
		s[i + 1] = -1;
		s[i + 2] = 6;
	}
	clock_t t_0, t;
	t_0 = clock();
	max_sum = MaxSum_1(s, 1000);
	t = clock()-t_0;
	cout << "1:" << endl;
	cout << "时间:" << t << "毫秒" << endl;
	cout << "maxsum_1 = " << max_sum << endl;
	t_0 = clock();
	max_sum = MaxSum_2(s, 1000);
	t = clock() - t_0;
	cout << "2:" << endl;
	cout << "时间:" << t << "毫秒" << endl;
	cout << "maxsum_2 = " << max_sum << endl;
	t_0 = clock();
	max_sum = MaxSum_3(s, 1000);
	t = clock() - t_0;
	cout << "3:" << endl;
	cout << "时间:" << t << "毫秒" << endl;
	cout << "maxsum_3 = " << max_sum << endl;
	t_0 = clock();
	max_sum = MaxSum_4(s,0,999);
	t = clock() - t_0;
	cout << "4:" << endl;
	cout << "时间:" << t << "毫秒" << endl;
	cout << "maxsum_4 = " << max_sum << endl;
	cin.get();
	return 0;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值