Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 98850 Accepted Submission(s): 22737
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
贪心算法:
#include<stdio.h> int main() { int m; //case数 int n; // 数列长度 int i,j; int p,start,temp,end; int max,sum; scanf("%d",&m); for(i = 1; i <= m; i++) { sum = 0; temp = 1; // 扫描到的第一个子段肯定是起始位置为1 max = -1001; scanf("%d",&n); for(j = 1; j <= n; j++) { scanf("%d",&p); sum += p; if(sum > max) { max = sum; // 遇到更大的子段和,更新起始,结束位置 start = temp; end = j; } if(sum < 0) { sum = 0; //当前子段和归零 temp = j + 1; //下一位置为起始位 } } printf("Case %d:\n%d %d %d\n",i,max,start,end); if(i < m) printf("\n"); } return 0; }
动态规划
#include<cstdio> using namespace std; int dp[100010]; // dp[i]存储以第i个元素为结尾的最大子段和 int main() { int T; scanf("%d", &T); for(int I = 1;I <= T; I++) { int n,start = 1,end = 1,ans, temp = 1; scanf("%d",&n); for(int i = 1;i <= n;i ++) scanf("%d",dp + i);
ans = dp[1]; for(int i = 2;i <= n;i ++) { int t = dp[i] + dp[i - 1]; if(t >= dp[i]) //如果加上第i个元素比之前的和大,
dp[i] = t; //那么第i个元素为结尾的最大子段和 else //就是第i个元素和前一个元素为结尾的最大子段和的和 temp = i; if(ans < dp[i]) //如果以第i个元素为结尾的最大子段和比当前最大的还大,就更新 { ans = dp[i]; start = temp; end = i; } } printf("Case %d:\n",I); printf("%d %d %d\n",ans,start,end); if(I < T)printf("\n"); } return 0; }通过滚动数组减少内存的动态规划
#include<cstdio> using namespace std; int main() { int T, dp[2]; //因为再上一个代码里面dp[i]只是和前一个元素dp[i - 1]有关系, scanf("%d", &T); //所以没必要开那么大的数组,每次用完i-1个元素就可以覆盖它 for(int I = 1;I <= T; I++) { int n, start = 1, end = 1, ans, temp = 1; scanf("%d",&n); scanf("%d",&ans); dp[0] = ans; for(int i = 2,j = 1;i <= n;i ++) { scanf("%d",dp + j); int t = dp[j] + dp[j ^ 1]; if(t >= dp[j]) dp[j] = t; else temp = i; if(ans < dp[j]) { ans = dp[j]; start = temp; end = i; } j ^= 1; } printf("Case %d:\n",I); printf("%d %d %d\n",ans,start,end); if(I < T)printf("\n"); } return 0; }