码迷,mamicode.com
首页 > 其他好文 > 详细

HD 1003 Max Sum 的递归解法

时间:2015-04-19 06:19:02      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include <STDIO.H>
 2 typedef struct SU_tag{
 3     SU_tag(){}
 4     SU_tag(int a,int b,int c):max_sum(a),left(b),right(c){}
 5     int max_sum;
 6     int left;
 7     int right;
 8 }SU;
 9 
10 SU find_max_crossing_subarray(int *a,int low,int mid,int high)
11 {
12     int left,left_max=a[mid],right,right_max=a[mid+1],i,sum;
13     sum=0;
14     for(i=mid;i>=low;i--){
15         sum+=a[i];
16         if(sum>=left_max){
17             left_max=sum;
18             left = i;
19         }
20     }
21     sum=0;
22     for(i=mid+1;i<=high;i++){
23         sum+=a[i];
24         if(sum>=right_max){
25             right_max = sum;
26             right = i;
27         }
28     }
29     return SU(left_max+right_max,left,right);
30 }
31 
32 SU find_max_subarray(int *a,int low,int high)
33 {
34     SU left,right,cross;
35     if(low == high){
36         return SU(a[low],low,high);
37     }else{
38         int mid = (low+high)/2;
39         left = find_max_subarray(a,low,mid);
40         right = find_max_subarray(a,mid+1,high);
41         cross = find_max_crossing_subarray(a,low,mid,high);
42     }
43     if(left.max_sum>=right.max_sum && left.max_sum>=cross.max_sum)
44         return left;
45     else if(cross.max_sum>=left.max_sum && cross.max_sum>=right.max_sum)
46         return cross;
47     else
48         return right;
49 }
50 
51 int main()
52 {
53     int t,n,i;
54     scanf("%d",&t);
55     i = 1;
56     while(i<=t){
57         scanf("%d",&n);
58         int m=0,*a=new int[n];
59         for(;m<n;m++)
60             scanf("%d",&a[m]);
61         SU r = find_max_subarray(a,0,n-1);
62         printf("Case %d:\n",i);
63         printf("%d %d %d\n",r.max_sum,r.left+1,r.right+1);
64         if(i!=t)
65             printf("\n");
66         delete a;
67         i++;
68     }
69     return 0;
70 }

 

HD 1003 Max Sum 的递归解法

标签:

原文地址:http://www.cnblogs.com/tangxin-blog/p/4438546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!