HDU 1003——Max Sum【最大子序列和】

mac2024-04-12  29

题目传送门


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


题意:

给定序列个数n及n个数,求该序列的最大连续子序列的和,要求输出最大连续子序列的和以及子序列的首位位置


分析:

常规求解子序列和问题,但是加了首尾位置sum维护当前首尾指向的区间和,maxi记录最大值 1、如果sum < 0,舍去即可,因为一定导致后面的值变小,不如直接选后面的值 2、如果sum > maxi,更新最大值注意结尾换行

AC代码:

#include <iostream> #include <vector> #include <utility> #include <cstring> #include <string> #include <algorithm> #include <map> #include <queue> #include <stack> #include <cstdio> #include <fstream> #include <set> using namespace std; typedef long long ll; const int INF = 0x3f3f3f; const int MAXN = 1e5 + 100; int a[MAXN]; int dp[MAXN]; int main() { int T; cin >> T; for (int z = 1; z <= T; z++) { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } int maxi = -INF; int start = 0; int end = 0; int sum = 0; int ts = 0, te = 0; while (end < n) { sum += a[end]; if (sum > maxi) { maxi = sum; ts = start; te = end; } if (sum < 0) { sum = 0; start = end + 1; } end++; } if (z != 1) cout << endl; cout << "Case " << z << ":" << endl << maxi << " " << ts + 1 << " " << te + 1 << endl; } return 0; }
最新回复(0)