Topic links: http://acm.hdu.edu.cn/showproblem.php?pid=1231
Given a sequence of K integers {N1, N2, ..., NK }, any of which can be expressed as contiguous subsequence of Ni {, of Ni + . 1 , ..., Nj}, where . 1 <= I <= J <= K. Maximum continuous sequence is all consecutive sequence elements and the largest, for example, a given sequence { - 2 , 11 - . 4 , 13 - . 5 - 2 }, the maximum consecutive sub-sequence { 11 - . 4 , 13 }, and the maximum 20. In this year's data structure in the papers, and requires programming to get the maximum increase is now a requirement that also need to output the first and the last element sequence.
First, we think of n ^ 2 practice is to first find a prefix and then enumerate the start and end the largest sequence. However, this problem is data range n <= 10000, and a plurality of sets of data, the approach is n ^ 2 will timeout. So how should optimize it?
This question Correct answer is dp, dp [i] represents the largest sub-sequences i and ending, so the end is fixed, while the starting point is random, so I am sure to find the best starting point, to 2, for example, if the first an element is positive, then I will be added to dp [2] on, if it is negative, then dp [2] is the largest a [2] the same and so on, dp [i] can be obtained with as i the end of the maximum sequence and so if dp [i-1] is negative, then dp [i] = a [i] (a [i] that is i-th element of the original sequence), or dp [i] = dp [i-1] + a [i], so that finally only need to scan over the array dp can know how much of the maximum sequence and are.
This problem also requires start-stop two output elements, so the processing at code:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int n; 5 int a[10005]; 6 int dp[10005]; 7 int s[100005]; 8 int ans; 9 int t1,t2; 10 int main() 11 { 12 while(1) 13 { 14 scanf("%d",&n); 15 if(n==0)break; 16 ans=-1; 17 for(int i=1;i<=n;++i)scanf("%d",&a[i]),s[i]=s[i-1]+a[i]; 18 for(int i=1;i<=n;++i) 19 dp[i]=max(dp[i-1]+a[i],a[i]); 20 t1=1,t2=n; 21 for(int i=1;i<=n;++i) 22 if(dp[i]>ans)ans=dp[i],t2=i; 23 if(t2==n&&ans==-1) 24 { 25 printf("0 %d %d\n",a[1],a[n]); 26 }else 27 { 28 for(int i=1;i<=t2;++i) 29 if(s[t2]-s[i-1]==ans) 30 { 31 t1=i;break; 32 } 33 printf("%d %d %d\n",ans,a[t1],a[t2]); 34 } 35 } 36 return 0; 37 }