最大子段和问题

最大子段和问题(Visual Studio 2010):

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	void Display(int* pp,int s,int t);
	int MaxSubSum(int* pp,int* ppt,int s,int t);
	int len;
	cout<<"Please input the array length:"<<endl;
	cin>>len;
	int* p=new int[len];// array
	int* pt=new int[3];pt[0]=0;pt[1]=0;pt[2]=0;
	cout<<"Please input the element datas:"<<endl;
	int d;
	for(int i=0;i<len;i++)
	{
		cin>>d;
		p[i]=d;//initate the heap
	}
	Display(p,0,len-1);
	cout<<"MaxSubSum cacular begins。。。"<<endl;
	MaxSubSum(p,pt,0,len-1);
	cout<<"s:"<<pt[0]<<",t:"<<pt[1]<<",maxVal:"<<pt[2]<<endl;
	cout<<"The maxsub is:"<<endl;
	Display(p,pt[0],pt[1]);
	system("pause");
	return 0;
}
//序列形如(5 6 8 9 7 -8 -2 9),pt=[s,t,maxsub(p)]
int MaxSubSum(int* p,int* pt,int s,int t)
{
	int templeft=0,lefts=0,tempright=0,rights=0,maxVal=0;
	int ls=0,rt=0;
	if(s==t){
		if(p[s]>=0){		
		pt[0]=s;pt[1]=t;pt[2]=p[s];	
		}else{
			pt[2]=0;
		}
		return pt[2];
	}
	int m=(s+t)/2;
	int leftmaxVal=MaxSubSum(p,pt,s,m);
	int rightmaxVal=MaxSubSum(p,pt,m+1,t);
	for(int i=m;i>=s;i--){//左半部分最大子段
		lefts=lefts+p[i];
		if(templeft<=lefts){
			templeft=lefts;
			ls=i;
		}
	}
	for(int j=m+1;j<=t;j++){//右半部分最大子段
		rights=rights+p[j];
		if(tempright<=rights){
			tempright=rights;
			rt=j;
		}
	}
	cout<<"s="<<s<<",t="<<t<<endl;
	cout<<"pt[0]="<<pt[0]<<",pt[1]="<<pt[1]<<",pt[2]="<<pt[2]<<endl;
	/*cout<<"ls="<<ls<<",rt="<<rt<<",tempright="<<tempright<<",templeft="<<templeft<<endl;
	cout<<"leftmaxVal="<<leftmaxVal<<",rightmaxVal="<<rightmaxVal<<endl;*/
	cout<<"\n"<<endl;
	maxVal=templeft+tempright;
	if(maxVal<rightmaxVal){
		maxVal=rightmaxVal;
	}
	if(maxVal<leftmaxVal){
		maxVal=leftmaxVal;
	}
	pt[0]=ls;pt[1]=rt;
	pt[2]=maxVal;
	return pt[2];
}


//output
void Display(int* p,int s,int t)
{
	cout<<"Now the array is:"<<endl;
	for(int i=s;i<=t;i++)
	{
		cout<<p[i];
		if(i<t)
		{
			cout<<",";
		}
	}
	cout<<"\n";
}


转载于:https://my.oschina.net/kongdf/blog/884880

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值