Maximum continuous subsequence
Time Limit: 2000/1000 MS (Java/others) memory limit: 65536/32768 K (Java/others) total submission (s): 19377 accepted submission (s): 8627
Problem description
Given K integer sequences {N1, N2,..., nk}, any continuous subsequences can be represented as {Ni, Ni + 1 ,...,
NJ}, where 1 <= I <= j <= K. The maximum continuous subsequence is the element and the largest of all consecutive subsequences,
For example, for a given sequence {-2, 11,-4, 13,-5,-2}, its maximum continuous subsequence is {11,-4, 13}, the largest and
Is 20.
In this year's data structure examination paper, the maximum sum of programming requirements is required. Now, a requirement is added, that is,
The first and last elements of the subsequence.
Input
The test input contains several test cases. Each test case occupies two rows. Row 1st provides a positive integer k (<10000), and row 2nd provides K integers separated by spaces. When K is 0, the input ends and the case is not processed.
Output
For each test case, the first and last elements of the largest sum and maximum continuous subsequences are output in one row.
, Separated by spaces. If the maximum continuous subsequence is not unique, the smallest sequence numbers I and j are output (for example, 2nd and 3 groups in the input sample ). If all k elements are negative, the maximum value is 0, and the first and last elements of the entire sequence are output.
Sample Input
6
-2 11-4 13-5-2
10
-10 1 2 3 4-5-23 3 7-21
6
5-8 3 2 5 0
1
10
3
-1-5-2
3
-1 0-2
0
Sample output
20 11 13
10 1 4
10 3 5
10 10 10
0-1-2
0 0 0
Hint
Hint
Huge input, scanf is recommended.
Source
Zhejiang University Computer postgraduate review computer examination-2005
The sum of the first element, the last element, and the Child Sequence
Idea: the method of dynamic planning is mainly to find the state transition equation. Accumulate and add the current value
Compare with the current value. If you accumulate and add the current value> current value, add the current value,
The last element changes to I. If you accumulate and add the current value <current value, sum [I] = A [I]
And change the first element to I, and the last element to I. For more information, see the code.
State transition equation: sum [I] = max (sum [I-1] + A [I], a [I]);
<span style="font-family:Microsoft YaHei;font-size:18px;"># include<stdio.h># include<string.h>int num[10010];int main(){ int i,K,sum,flag,a,b,a1,b1; while(scanf("%d",&K) && K!=0) { memset(num,0,sizeof(0)); for(i=0;i<K;i++) scanf("%d",&num[i]); sum = 0; a1 = a = flag = num[0]; b1 = b = num[K-1]; for(i=0;i<K;i++) { sum += num[i]; if(sum>0) { b = num[i]; } else { sum = 0; if(num[i+1]>=0) a = b = num[i+1]; } if(sum > flag) { a1 = a; b1 = b; flag = sum; } } if(flag < 0) printf("0 %d %d\n",num[0],num[K-1]); else printf("%d %d %d\n",flag,a1,b1); } return 0;}</span>
Hdu1231 _ maximum continuous subsequence