【算法】HDOJ-1003 Max Sum

来源:互联网 发布:qq无限加人软件 编辑:程序博客网 时间:2024/06/08 09:38

Max Sum

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


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 

Author
Ignatius.L
 
Code:
提交时注意数据规模,我前几次提交数组只定义了1001,全部WA,后来发现原题中规定1<=N<=100000,so把数组大小改为了100001。
 

#include <stdio.h>

using namespace std;

int main(){    int f[100001];    int T,N,i,start,end,count=1,sum,Max,k;    scanf("%d",&T);    while(T--){        sum=0,Max=-99999;        k=1,start=1;end=1;        scanf("%d",&N);        for(i=1;i<=N;i++){            scanf("%d",&f[i]);            sum+=f[i];            if(sum>Max){                Max=sum;                start=k;                end=i;            }            if(sum<0) {                k=i+1;                sum=0;            }        }        printf("Case %d:\n",count++);        printf("%d %d %d\n",Max,start,end);        if(T!=0) printf("\n");    }    return 0;}

 

第二种方法运用动态规划,动态转移方程为f[i]=max{f[i-1]+f[i],f[i]},由此得出程序:

 

#include <stdio.h>using namespace std;int main(){    int f[100001];    int start,end;    int i,T,N,count=1;    scanf("%d",&T);    while(T--){        int q[100001];        q[1]=1;        start=1; end=1;        scanf("%d",&N);        for(i=1;i<=N;i++){            scanf("%d",&f[i]);            if(i==1) continue;            if(f[i-1]+f[i]>=f[i]) {f[i]=f[i-1]+f[i];q[i]=0;}            else q[i]=1;            if(f[i]>f[end]) {end=i;}        }        for(i=end;i>0;i--)            if(q[i]==1) {start=i;break;}        printf("Case %d:\n",count++);        printf("%d %d %d\n",f[end],start,end);        if(T!=0) printf("\n");    }    return 0;}


 

原创粉丝点击