HDU 1003 Max Sum(动态规划)
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
题目链接
这篇博文对这类最大子序列和题目的解释很详细,我看了之后感觉通俗易懂,自己照着这个动态规划的思路写了一遍,但是找起点和终点的位置我是按照自己的想法写的,算法会有点复杂。这道题目每组数据之间有空行输出,最后一组之后没有;ans的初始值一定要赋值为一个比较小的负数,因为题目数据是-1000~1000。
AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <set>
#include <map>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define pb push_back
typedef long long ll;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+5;
const double eps = 1e-5;
const double e = 2.718281828459;
int num[maxn];
int maxsum[maxn];
int find_left(int x) {
int sum = 0, ans = INF;
for (int i = x; i >= 1; --i) {
sum += num[i];
if (sum == maxsum[x]) {
if (i < ans) {
ans = i;
}
}
}
return ans;
}
bool cmp(int a, int b) {
return a > b;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
maxsum[0] = 0;
int t;
cin >> t;
for (int Case = 1; Case <= t; ++Case) {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> num[i];
maxsum[i] = max(maxsum[i - 1] + num[i], num[i]);
}
int ans = -INF, right = 1, left = 1;
for (int i = 1; i <= n; ++i) {
if (maxsum[i] > ans) {
ans = maxsum[i];
right = i;
left = find_left(i);
}
}
cout << "Case " << Case << ":" << endl;
cout << ans << " " << left << " " << right << endl;
if (Case != t) {
cout << endl;
}
}
return 0;
}