PAT (Advanced Level) 1007. Maximum Subsequence Sum (25) 经典题
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:
10 -10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
题意:经典的求最大连续子序列和一点点的加难版。
题解:做法很多,数据结构的书介绍时间复杂度时作为例题分析过,除了O(n^2)的DP外可以用分治,以及题目要求的特殊性可以使用O(n)的算法。
1 #include <stdio.h> 2 #include <iostream> 3 using namespace std; 4 5 int a[10010]; 6 int main() 7 { 8 int n, flag = 0; 9 scanf("%d", &n); 10 for(int i = 0; i < n; i++) 11 { 12 scanf("%d", a + i); 13 if(a[i] >= 0) 14 flag = 1; 15 } 16 int ans = 0; 17 int tl, tr, t; 18 int l, r, ma; 19 l = r = 0; 20 tl = tr = t = 0; 21 //t = a[0]; 22 ma = 0; 23 for(int i = 0; i < n; i++) 24 { 25 if(t + a[i] <= 0) 26 { 27 if(t > ma) 28 { 29 ma = t; 30 l = tl; 31 r = tr; 32 } 33 t = 0; 34 tl = i + 1; 35 tr = i + 1; 36 } 37 else 38 { 39 t += a[i]; 40 tr = i; 41 if(t > ma) 42 { 43 ma = t; 44 l = tl; 45 r = tr; 46 } 47 48 } 49 //cout << l << "~" << r << endl; 50 } 51 if(ma > 0) 52 printf("%d %d %d\n", ma, a[l], a[r]); 53 else if(ma==0 && flag) //特判 -1 0 -1 情况 54 printf("0 0 0\n"); 55 else printf("0 %d %d\n", a[0], a[n-1]); 56 57 }