Maximum continuous subsequenceTime
limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 23078 Accepted Submission (s): 10282
Problem description A sequence of k integers {N1, N2, ..., NK}, any contiguous subsequence can be expressed as {Ni, ni+1, ...,
Nj}, where 1 <= i <= J <= K. The maximal contiguous subsequence is the element and the largest of all successive subsequence sequences,
For example, given sequence {-2, 11,-4, 13,-5,-2}, its maximum contiguous subsequence is {11,-4, 13}, Max
to 20.
In this year's data structure exam, it is required to write the program to get maximum and, now add a requirement, that also need to output the
The first and last elements of a subsequence.
The input test inputs contain several test cases, each with 2 rows, a positive integer k (< 10000) in line 1th, and a K integer in line 2nd, separated by a space. When k is 0 o'clock, the input ends and the use case is not processed.
Output for each test case, the first and last elements of the largest and longest contiguous subsequence are exported in 1 rows
The middle is separated by a space. If the maximum consecutive subsequence is not unique, the output sequence number I and J is the smallest one (as in the 2nd, 3 groups of the input sample). If all k elements are negative, define their maximum and 0, outputting the entire sequence of the first and the end elements.
Sample Input
6-2 11-4 13-5-210-10 1 2 3 4-5-23 3 7-2165-8 3 2 5 01103-1 -5-23-1 0-20
Sample Output
1310 1 410 3 510 100-1 -20 0 0HintHintHuge input, scanf is recommended.
The subject uses the idea of dynamic programming, defines 3 arrays, namely DP (state), a (record data), S (record start subscript);The state transition equation is: Dp[i]=max (Dp[i-1]+a[i],a[i]);Core code:for (int i=1;i<=k;i++)
{
if (Dp[i-1]+a[i]>a[i])
{
Dp[i]=dp[i-1]+a[i];
S[I]=S[I-1];
}
Else
{
Dp[i]=a[i];
S[i]=i;
}
}
The complete code is as follows:
#include <iostream> #include <cstdio> #include <cstring>using namespaceStd; int A[10001]; int Dp[10001]; int S[100001]; int Main () { int K,Max,Start,End,Flag; while (Cin>>K,K) {Flag=0;Memset(Dp,0 ,sizeof( Dp));Memset(A,0 ,sizeof( A));//memset (s,0,sizeof (s));S[0]=S[1]=1; for (int I=1;I<=K;I++) {Cin>>A[I]; if (A[I]>=0)Flag=1; } if( Flag==1 ) { for(int I=1;I<=K;I + +) { if( Dp[I-1]+A[I]>A[I]) {Dp[I]=Dp[I-1]+A[I];S[I]=S[I-1]; } Else { Dp[I]=A[I];S[I]=I; } }Max=Dp[1];Start=1;End=1; for (int I=2;I<=K;I + +) { if( Max<Dp[I]) {Max=Dp[I];Start=S[I];End=I; } }cout<<Max<<" "<<A[Start]<<" "<<A[End]<<Endl; } Else { cout<<"0"<<" "<<A[1]<<" "<<A[K]<<Endl; }} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hangzhou Electric (HDU) ACM 1231 maximum continuous subsequence