ACM资料大集合

源代码在线查看: 求最大子段和问题,分治递归法.txt

软件大小: 803 K
上传用户: jessica12332145
关键词: ACM
下载地址: 免注册下载 普通下载 VIP

相关代码

				#include 
				#include 
				#include 
				
				//求最大子段和问题,分治递归法
				/*
				输入:
				9
				-20 11 3 -2 15 -30 12 1 5
				
				输出:
				27
				*/
				int maxsum(int s[],int left,int right)
				{
					int center;
					int sumleft,sumright,sumcenter,s1,s2,i,temp;
					if(left==right) 
					{
						if(s[left]>0) sumcenter=s[left];
						else
							sumcenter=0;
					}
					else{
					center=(left+right)/2;
					sumleft=maxsum(s,left,center);
					sumright=maxsum(s,center+1,right);
					s1=temp=0;
					for(i=center;i>=left;i--)
					{
						temp+=s[i];
						if(s1					}
					s2=temp=0;
					for(i=center+1;i					{
						temp+=s[i];
						if(s2					}
					sumcenter=s1+s2;
					if(sumcenter					if(sumcenter					}
					return sumcenter;
				}
				
				
				int main()
				{
					int s[10],num,i,answer;
					scanf("%d",&num);
					for(i=0;i						scanf("%d",&s[i]);
					answer=maxsum(s,0,num-1);
					printf("answer=%d\n",answer);
					return 0;
				}			

相关资源