zoukankan      html  css  js  c++  java
  • HD 1003 Max Sum 的递归解法

     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:
    ",i);
    63         printf("%d %d %d
    ",r.max_sum,r.left+1,r.right+1);
    64         if(i!=t)
    65             printf("
    ");
    66         delete a;
    67         i++;
    68     }
    69     return 0;
    70 }
  • 相关阅读:
    Java 中的数组操作
    WinForm 无边框窗体、后台创建控件、timer控件
    WinForm 进程与线程
    WinForm messageboxbuttons 和 三级联动
    WinForm ListView控件属性及用法
    WinForm 多窗体、菜单和工具栏控件
    WinForm 小练习订餐界面
    WinForm 公共控件及其常用属性
    WinForm 常用属性及控件
    ADO.NET 数据访问类查询、属性扩展
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/4438546.html
Copyright © 2011-2022 走看看