HDU1003 最大连续子序列
Posted fangxiaoqi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU1003 最大连续子序列相关的知识,希望对你有一定的参考价值。
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 324393 Accepted Submission(s): 77146
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
【题意】
给定一个序列a[1],a[2],a[3],.....,a[n],来计算子序列的最大和。例如,给定序列(6,-1,5,4,-7),这个序列中的最大和是 6 +(-1)+ 5 + 4 = 14。
输入的第一行包含一个整数T(1<=T<=20),它表示测试用例的数量。然后是T行,每一行以N开头(1<=N<=100000),然后是N个整数(所有整数都在-1000到1000之间)
对于每个测试用例,输出两行。第一行是“Case #:”,#表示测试用例的数量。第二行包含三个整数,序列中的最大和,子序列的起始位置,子序列的结束位置。如果有多个结果,输出第一个。在两种情况之间输出空行。
【代码】
#include <stdio.h> #include <stdlib.h> int main(){ int i,j,n,t; scanf("%d",&t); for(i=1;i<=t;i++){ int *a,first=0,last=0,sum=0,tmp=1,max=-1001; scanf("%d",&n); a=(int*)malloc(n*sizeof(int)); for(j=0;j<n;j++){ scanf("%d",&a[j]); sum += a[j]; if(sum>max){ max=sum; first=tmp; last=j+1; } if(sum<0){ sum=0; tmp=j+2; } } printf("Case %d:\n%d %d %d\n",i,max,first,last); if(i!=t)printf("\n"); a=NULL; } return 0; }
以上是关于HDU1003 最大连续子序列的主要内容,如果未能解决你的问题,请参考以下文章