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
题解:
动态规划的题目,以前遇到过这道题,当时用了两个数组,直接计算,结果不得而知 TLE。然后就没做,这次又碰到了,理解了动态规划思想以后,对这题的解法有了新的思路 以下是变量说明: t 测试数据组数 n 每组数据的长度 a[i] 当前取的数据MIN_N 最后MAX SUM的起始位置MAX_N 最后MAX SUM的结束位置
MAX_sum 当前得到的MAX SUM sum 在读入数据时,能够达到的最大和k 记录最大和的起始位置,因为不知道跟之前的max值的大小比,所以先存起来m 记录最大和的终止位置,因为不知道跟之前的max值的大小比,所以先存起来下面模拟过程:1.首先,读取第一个数据,令MAX_sum等于第一个数据,初始化MIN_N,MAX_N,k,m位置和 sum 的值2.然后,读入第二个数据,判断①. 若是sum > MAX_sum,表示当前的数据和 比 之前存储的数据和大,更新一下储存
②. 若是 sum < 0, 那么该项肯定不适合再往后加,所以,把 sum 复制成 0 ,在当前位置开始加3.遍历一遍以后输出结果
附上代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <vector> #define INF 0x3f3f3f3f using namespace std; int a[100010]; int main() { int t,num = 1; cin >> t; while(t--) { int n; cin >> n; memset(a,0,sizeof(a)); for(int i = 1;i <= n;i++) { scanf("%d",&a[i]); } long long int sum = 0; int MIN_N = 1,MAX_N = 1,MAX_sum = a[1]; int k = 1,m = 1; for(int i = 1;i <= n;i++) { sum += a[i]; m = i; if(sum > MAX_sum) // 如果当前加的值比原来的大,进行一次更新 { MAX_sum = sum; MIN_N = k; MAX_N = m; } if(sum < 0) // 如果当前的值为 负 的,那么肯定不适合往下加,因为往下加肯定比下一个开始加的结果小,所以 给 sum 赋值为 0,然后做一个初始位置的标记。 { sum = 0; k = i + 1; m = i + 1; } } if(num > 1) printf("\n"); printf("Case %d:\n",num++); cout << MAX_sum << " " << MIN_N << " " << MAX_N << endl; } return 0; }