杭电 Problem-1003 Max Sum【dp】
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 200384 Accepted Submission(s): 46853
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
思路:
对于第i个数,它只有两种状态,一个是接在前一个队伍的前面,另一个是自己作为队头元素。dp[i]中存放的应该在i位置时i位置所属队伍的值。所以统计dp中最大的值就可以知道所有队伍中的最值。据此,只需要保证dp[i]的值最大就可以。
so 状态转移方程为:dp[i]=max(dp[i-1]+a[i], a[i]);
对于第i个数,它只有两种状态,一个是接在前一个队伍的前面,另一个是自己作为队头元素。dp[i]中存放的应该在i位置时i位置所属队伍的值。所以统计dp中最大的值就可以知道所有队伍中的最值。据此,只需要保证dp[i]的值最大就可以。
so 状态转移方程为:dp[i]=max(dp[i-1]+a[i], a[i]);
#include <bits/stdc++.h> #define MAXN 100005 using namespace std; int dp[MAXN], ar[MAXN], s[MAXN]; int main() { int t, cnt = 0; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &ar[i]); } dp[1] = ar[1]; int loc = 1; s[1] = 1; for (int i = 2; i <= n; i++) { dp[i] = max(dp[i-1] + ar[i], ar[i]); if (dp[i - 1] + ar[i] >= ar[i]) { s[i] = loc; dp[i] = dp[i - 1] + ar[i]; } else { dp[i] = ar[i]; loc = s[i] = i; } } int ans = -1e9, e; for (int i = 1; i <= n; i++) { if (dp[i] > ans) { ans = dp[i]; e = i; } } printf("Case %d:\n%d %d %d\n", ++cnt, ans, s[e], e); if (t) printf("\n"); } return 0; }
另外的解法
#include <stdio.h> int main() { int a, b, t, m, n, Case=0, max, temp; scanf("%d", &t); while(t--) { Case++; scanf("%d", &n); int sum = 0; max = -10e5; temp = 1; for (int i = 1; i <= n; i++) { scanf("%d", &m); sum += m; if(sum > max) { b = i; max = sum; a = temp; } if(sum < 0) { temp = i + 1; sum = 0; } } printf("Case %d:\n", Case); printf("%d %d %d\n", max, a, b); if(t != 0) { printf("\n"); } } return 0; }