Max 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).
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 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
Author
Ignatius.L
题目类型:线性DP
算法分析:这是求最大子序列和的经典问题,ans[i]定义为第i个数字之前的最大子序列和,val[i]为读入的int型数组,状态转移方程为:如果ans[i-1] < 0, 则ans[i] = val[i];否则ans[i] = ans[i-1] + val[i]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include <iostream> #include <fstream> #include <algorithm> #include <iomanip> #include <cstring> #include <cstdio> #include <cmath> #include <map> #include <string> #include <vector> #include <stack> #include <queue> #include <set> #include <list> #include <ctime> using namespace std; const int maxn = 100000 + 66; const int INF = 0x7FFFFFFF; int input[maxn]; int main() { // ifstream cin ("aaa.txt"); int t, flag = 1; cin >> t; while (t--) { int n; cin >> n; int i; for (i = 0; i < n; i++) cin >> input[i]; int s = 0, e = 1, maxval = -INF, tempsum = 0, ss = 0; for (i = 0; i < n; i++) { tempsum += input[i]; if (tempsum > maxval) { maxval = tempsum; s = ss + 1; e = i + 1; } if (tempsum < 0) { tempsum = 0; ss = i + 1; } } if (flag - 1) cout << endl; cout << "Case " << flag++ << ":" << endl; cout << maxval << " " << s << " " << e << endl; } return 0; } |
- hdu1004:下一篇 »