HDU 1003 Max Sum
阿新 • • 發佈:2017-08-01
star 比較 esc 思路 ++ n) scan input script
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 -15 4 -7
7 0 6 -1 1 -6 7 -5
輸入一串數字為N N(1<=N<=100000)和N個範圍-1000到1000的整型數 計算並輸出該串數字的最大子串(連續)和以及該子串的起始位置和終止位置 解題思路:
該題還是比較考察思維的,屬於簡單的DP問題。遍歷每個元素,將其累加到sum上,並每次判斷sum是否大於max,若大於max則更新sum後,將始末位置也更新一下;若sum<0,表示該數是一個很大的負數需要重新開始累加sum,尋找下一個可能存在的最大子串和。 代碼實現:
題目:
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).
Sample Output Case 1: 14 1 4 Case 2: 7 1 6 題意描述:
輸入一串數字為N N(1<=N<=100000)和N個範圍-1000到1000的整型數 計算並輸出該串數字的最大子串(連續)和以及該子串的起始位置和終止位置 解題思路:
該題還是比較考察思維的,屬於簡單的DP問題。遍歷每個元素,將其累加到sum上,並每次判斷sum是否大於max,若大於max則更新sum後,將始末位置也更新一下;若sum<0,表示該數是一個很大的負數需要重新開始累加sum,尋找下一個可能存在的最大子串和。 代碼實現:
1 #include<stdio.h> 2 int main() 3 { 4 int T,t,n,a[100010],i,sum,s,f,c=0,max; 5 scanf("%d",&T); 6 while(T--) 7 { 8 scanf("%d",&n); 9 for(i=1;i<=n;i++) 10 scanf("%d",&a[i]); 11 sum=0; 12 max=-99999999;//註意將max賦值為一個較小的賦值 13 t=1; 14 for(i=1;i<=n;i++){ 15 sum += a[i]; 16 if(sum > max){ 17 max=sum; 18 s=t; 19 f=i; 20 } 21 if(sum < 0){ 22 sum=0; 23 t=i+1; 24 } 25 } 26 printf("Case %d:\n%d %d %d\n",++c,max,s,f); 27 if(T != 0) 28 printf("\n"); 29 } 30 return 0; 31 }
易錯分析:
1、註意格式問題
2、註意max的初始化
HDU 1003 Max Sum