zoukankan      html  css  js  c++  java
  • hdu_1003_Max Sum

    Max Sum

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 142281    Accepted Submission(s): 33104

    Problem Description
    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
     
    Input
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
     
    Output
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
     
    Sample Input
    2
    5 6 -1 5 4 -7
    7 0 6 -1 1 -6 7 -5
     
    Sample Output
    Case 1:
    14 1 4
     
    Case 2:
    7 1 6
     
    问题的想法是《编程之美》上的,修改了一下提交就ok了。。
    思路:
       考虑数组的第一个元素a[0],以及最大的一段数组(a[i].....a[j])跟a[0]之间的关系,有一下几种情况:
         1. 当0=i=j时,元素a[0]本身构成和最大的一段。
         2.当0=i<j时,和最大的一段以a[0]开始。
         3.当0<i时,元素a[0]跟和最大的一段没有关系。
    假设已经知道(a[1]....a[n-1])中的最大的一段数组之和为All[1],并且已经知道了(a[1]......a[n-1])中包含a[1]的和最大的一段数组为start[1]。
    那么有以上情况可以得出(a[0].....a[n-1])中问题的解All[0]是三种情况的最大值max(a[0],a[0]+start[1],All[1]).
    so问题符合无后效性,用动态规划方法可解决。
       
     1 #include<iostream>
     2 using namespace std;
     3 int main()
     4 {
     5     int t,len,m=0,h,n,w,l,r,p,e,i;
     6     cin>>t;h=t;
     7     while(t--)
     8     {
     9         m++;
    10         l=r=p=e=0;
    11         cin>>len;
    12         int a[len];
    13         for(i=0;i<len;i++)
    14             cin>>a[i];
    15          n=a[0],w=a[0];l=0;p=0;
    16          for(i=1;i<len;i++)
    17          {
    18             if(a[i]>n+a[i]){
    19                 n=a[i];
    20                 l=i;
    21                 r=i;
    22             }
    23             else {
    24                 n=n+a[i];
    25                 r=i;
    26             }
    27             if(n>w){
    28                 w=n;
    29                 e=r;
    30                 p=l;
    31             }
    32         }
    33         cout<<"Case "<<m<<":"<<endl<<w<<" "<<p+1<<" "<<e+1<<endl;
    34         if(m!=h)cout<<endl;
    35     }
    36     return 0;
    37 }
  • 相关阅读:
    hdu 1754
    hdu 1166
    poj 1193
    如何由XSD自动生成XML和实体类
    WinForm(C#)CheckedlistBox绑定数据,并获得选中的值(ValueMember)和显示文本(DisplayMember)
    C#读写共享文件夹
    去除TFS版本控制信息
    SQL 触发器
    C#中操作WMI的类库-实现远程登录共享
    VS 制作安装包小窥
  • 原文地址:https://www.cnblogs.com/duanyuanzhi/p/3868801.html
Copyright © 2011-2022 走看看