HDU1003- Max Sum ------O(n)的解法

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<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define maxn 100000 + 5
#define INF -0xfffff
typedef long long ll;

using namespace std;

int a[maxn];
ll sum[maxn];
/*
//这个分治法,适合直接求最大值,但是不方便找出起始位置 
void maxnsum(int *a, l, r) {// a 相当于是一个数组,左闭右开 
	int mid = l + (r - l) / 2;
	ll maxs = max(maxsum(a, l, mid), maxsum(a, mid, r))
	ll v = 0, L, R;
	L = a[mid - 1];
	for(int i = mid - 1; i >= l; i--) {
		L = max(L, v += a[i]);
	}
	R = a[mid], v = 0;
	for(int j = mid; j < r; j++) {
		R = max(R, v += a[j]);
	}
	max = max(maxs, L + R);
}
*/
int l, r;
ll maxs;
void maxsum(int *a, int n) {
	sum[0] = 0;
	for(int i = 1; i <= n; i++)
		sum [i] = sum[i-1] + a[i];
	//求出前缀和
	int min = 1;
	maxs = sum[1];
	r = 1, l = 1;
	for(int i = 1; i < n; i++) {
		if(sum[i] < sum[min])
			min = i;// 最小值就是 sum [min]
		
		ll tmp = sum[i + 1] - sum[min];
		if(sum[i + 1] > tmp)
			tmp = sum[i + 1];
		if(tmp > maxs) {
			maxs = tmp;
			if(tmp == sum[i + 1]) {
				l = 1;
			}
			else l = min + 1;
			r = i + 1;
		}
	}// 0 0 2 0
}

int main() {
	int N = 0, n = 0;
	ll sum = 0;
	cin>>N;
	for(int j = 1; j <= N; j++) {
		memset(a, 0, sizeof(a));
		cin>>n;
		for(int i = 1; i <= n; i++) {
			cin>>a[i];
		}
		maxsum(a, n);
		cout<<"Case "<<j<<':'<<endl;
		cout<<maxs<<' '<<l<<' '<<r<<endl;
		if(j < N)
			cout<<endl;
	}
	
	return 0;
}
/*
准备的6 组样例 
/*
6
4 0 0 2 0
6 2 7 -9 5 4 3
4 0 0 -1 0 
7 -1 -2 -3 -2 -5 -1 -2
6 -1 -2 -3 1 2 3
5 -3 -2 -1 -2 -3
2 1 3
12 1 6
0 1 1
-1 1 1
6 4 6
-1 3 3
*/

猜你喜欢

转载自blog.csdn.net/qq_40830622/article/details/82907803