HDU 1003 解题报告

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 137277    Accepted Submission(s): 31816


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
 
分析:典型的求最大子序列和的问题,但是又有一些变化,需要知道当求得最大和时,子序列在元序列中的开始位置和结束位置。
首先,考虑暴力的方法,遍历整个序列,假定开始位置,然后去求当前开始位置下,任意结束位置的序列和,比较出最大的序列和即可。这样,时间复杂度为O(n^2)
进一步考虑,假设已经得到最大和的自序列,那么之所以这个自 序列不包含前面的几个或者后面几个元素的原因,就是因为前面(或者后面)连续几个元素的和是负数。这样,考虑子序列的结束位置,遍历0...n-1,假设当前位置为结束位置,那么如果以前面一个位置为结束的最大子序列和为负数时,只包含当前位置元素的子序列就是以当前位置结束的子序列的最大值;否则,以前面一个位置为结束的最大子序列和加上当前元素就是以当前位置结束的子序列的最大值。这样,按顺序遍历一遍,就可以得到以每个位置为结束位置的最大子序列的和,其中最大的就是整个序列最大子序列的和,时间复杂度O(n)。

代码:
#include<stdio.h>
int main(){
	int t, n, caseNum, maxSum, maxHere, beginMax, endMax, beginHere, endHere;
	int a[100002];
	scanf("%d", &t);
	caseNum = 0;
	while(t--){
		caseNum++;
		scanf("%d", &n);
		for(int i=0; i<n; i++){
			scanf("%d", &a[i]);
		}
		maxSum = -2147483647-1;
		maxHere = 0;
		beginMax = 0;
		endMax = 0;
		beginHere = 0;
		endHere = -1;
		for(int i=0; i<n; i++){
			if(maxHere<0){
				maxHere=a[i];
				beginHere = i;
				endHere = i;
			} else {
				maxHere+=a[i];
				endHere++;
			}
			if(maxHere>maxSum){
				maxSum = maxHere;
				beginMax = beginHere;
				endMax = endHere;
			}
		}
		printf("Case %d:\n", caseNum);
		printf("%d %d %d\n", maxSum, beginMax+1, endMax+1);
		if(t){
			printf("\n");
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值