最大子段和问题(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"; }
最大子段和问题
最新推荐文章于 2022-11-08 20:42:51 发布