其他分享
首页 > 其他分享> > 动态规划 三.最大子段和

动态规划 三.最大子段和

作者:互联网

例如,当a={-2,11,-4,13,-5,-2}时,最大子段和是20。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 #define N 100
 5 
 6 int maxsum1(int *a,int n)//动态规划算法 
 7 {
 8     int sum=0,b=0;
 9     for(int i=1;i<=n;i++)
10     {
11         if(b>0)b+=a[i];
12         else b=a[i];
13         if(b>sum)sum=b;
14      } 
15      return sum;
16 } 
17 
18 int maxsubsum(int *a,int left,int right)
19 {
20     int sum=0;
21     if(left==right) sum=a[left]>0?a[left]:0;
22     else 
23     {
24         int center=(left+right)/2;
25         int leftsum=maxsubsum(a,left,center);
26         int rightsum=maxsubsum(a,center+1,right);
27         int s1=0;
28         int lefts=0;
29         for(int i=center;i>=left;i--)
30         {
31             lefts+=a[i];
32             if(lefts>s1)s1=lefts;
33         }
34         int s2=0;
35         int rights=0;
36         for(int i=center+1;i<=right;i++)
37         {
38             rights+=a[i];
39             if(rights>s2)s2=rights;
40         }
41         sum=s1+s2;
42         if(sum<leftsum)sum=leftsum;
43         if(sum<rightsum)sum=rightsum;
44     }
45     return sum;
46 }
47 
48 int maxsum(int *a,int n)//分治算法 
49 {
50     return maxsubsum(a,1,n); 
51 }
52 
53 
54 int main()
55 {
56     int a[N],n;
57     cin>>n;
58     for(int i=1;i<=n;i++)
59     cin>>a[i];
60     cout<<"分治算法:" <<maxsum(a,n)<<endl; 
61     cout<<"动态规划算法:" <<maxsum1(a,n)<<endl;
62     return 0;
63 }

 

标签:right,center,子段,int,sum,lefts,动态,规划,left
来源: https://www.cnblogs.com/yuanqingwen/p/12753801.html