HDU1003 Max Sum 最大子序列和的问题【四种算法分析+实现】

就拿杭电OJ上的第1003题开始吧,这题比原书要复杂一些。

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>
#define maxn 100000 + 2
int arr[maxn];

int main(){
	int t, n, maxLeft, maxRight, maxSum, id = 1;
	int thisSum;
	scanf("%d", &t);
	while(t--){
		scanf("%d", &n);
		for(int i = 0; i < n; ++i)
			scanf("%d", &arr[i]);
		maxSum = arr[0];
		maxLeft = maxRight = 0;
		/*maxSubsequenceSum------O(N^3)*/
		for(int i = 0; i < n; ++i){
			for(int j = i; j < n; ++j){
				thisSum = 0;

				for(int k = i; k <= j; ++k){
					thisSum += arr[k];
				}
				if(thisSum > maxSum){
					maxSum = thisSum;
					maxLeft = i; maxRight = j;
				}
			}
		}
		printf("Case %d:\n%d %d %d\n", id++, maxSum, maxLeft + 1, maxRight + 1);
		if(t) printf("\n");
	}
	return 0;
}

结果是意料之中的超时

接下来我们再换一个效率高点的算法。其实上一个算法中第三层for循环可以去掉,让第二层表示以arr[i]为起点的子序列,就这样一直向右加下去,如果和大于maxSum,那么就更新值。实现如下:

#include <stdio.h>
#define maxn 100000 + 2
int arr[maxn]; 

int main(){
	int t, n, maxLeft, maxRight, maxSum, id = 1;
	int thisSum;
	scanf("%d", &t);
	while(t--){
		scanf("%d", &n);
		for(int i = 0; i < n; ++i)
			scanf("%d", &arr[i]);
		maxSum = arr[0];
		maxLeft = maxRight = 0;
		/*maxSubsequenceSum------O(N^2)*/
		for(int i = 0; i < n; ++i){
			thisSum = 0;
			for(int j = i; j < n; ++j){
				thisSum += arr[j];
				if(thisSum > maxSum){
					maxSum = thisSum;
					maxLeft = i;
					maxRight = j;
				}
			}
		}
		printf("Case %d:\n%d %d %d\n", id++, maxSum, maxLeft + 1, maxRight + 1);
		if(t) printf("\n");
	}
	return 0;
}

依旧超时

只能再换效率更高算法,对于最大子序列和这个问题其实可以细分成多个子问题来求解,再将子问题的解合并,于是可以考虑下分治法,具体实现如下:

#include <stdio.h>
#define maxn 100000 + 2
int arr[maxn];
int t, n, maxLeft, maxRight, maxSum, id = 1;

int max3(int a, int b, int c){
    if(a >= b && a >= c) return 1;
    if(b >= a && b >= c) return 2;
    if(c >= a && c >= b) return 3;
}

int maxSubsequenceSum(int left, int right, int *l, int *r){
    int thisLeft, thisRight;
    int leftSum, rightSum, midSum, mid;
    int leftBorderSum, maxLeftBorderSum;
    int rightBorderSum, maxRightBorderSum;
    int ll, lr, rl, rr, ml, mr;
    if(left == right){
		*l = *r = left;
		return arr[left];
	}
    mid = (left + right) / 2;
    leftSum = maxSubsequenceSum(left, mid, &ll, &lr);
    rightSum = maxSubsequenceSum(mid + 1, right, &rl, &rr);

    leftBorderSum = 0; thisLeft = mid;
    maxLeftBorderSum = arr[mid];
    for(int i = mid; i >= left; --i){
        leftBorderSum += arr[i];
        if(leftBorderSum >= maxLeftBorderSum){
            maxLeftBorderSum = leftBorderSum;
            thisLeft = i;
        }
    }
    rightBorderSum = 0; thisRight = mid + 1;
    maxRightBorderSum = arr[mid + 1];
    for(int i = mid + 1; i <= right; ++i){
        rightBorderSum += arr[i];
        if(rightBorderSum > maxRightBorderSum){
            maxRightBorderSum = rightBorderSum;
            thisRight = i;
        }
    }
    midSum = maxLeftBorderSum + maxRightBorderSum;   

    int sign = max3(leftSum, midSum, rightSum);

    if(sign == 1){
       maxSum = leftSum;
       *l = ll;
	   *r = lr;
    }else if(sign == 2){
        maxSum = midSum;
        *l = thisLeft;
		*r = thisRight;
    }else{
        maxSum = rightSum;
        *l = rl;
		*r = rr;
    }
    return maxSum;
}

int main(){
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        for(int i = 0; i < n; ++i)
            scanf("%d", &arr[i]);
        maxSum = arr[0];
        maxLeft = maxRight = 0;
        maxSubsequenceSum(0, n - 1, &maxLeft, &maxRight);
        printf("Case %d:\n%d %d %d\n", id++, maxSum, maxLeft + 1, maxRight + 1);
        if(t) printf("\n");
    }
    return 0;
}

终于AC了!

书上还介绍了一个狂拽酷炫叼炸天的O(n)算法,这里也尝试一下,再对比一下与分治法的时间消耗。改的过程真是相当得不顺利,WA了5次左右才改对,不过把数组开销都省了,真心够精简的。

#include <stdio.h>

int main(){
	int t, n, maxLeft, maxRight, maxSum, temp;
	int thisLeft, thisSum;
	scanf("%d", &t);
	for(int id = 1; id <= t; ++id){
		scanf("%d", &n);
		scanf("%d", &maxSum);
		thisLeft = maxLeft = maxRight =  0;
		thisSum = maxSum;
		if(thisSum < 0){ thisSum = 0; thisLeft = 1; }
		for(int i = 1; i < n; ++i){
			scanf("%d", &temp);
			thisSum += temp;
			if(thisSum > maxSum){
				maxSum = thisSum;
				maxLeft = thisLeft;
				maxRight = i;
			}
			if(thisSum < 0){
				thisLeft = i + 1;
				thisSum = 0;
			}
		}
		printf("Case %d:\n%d %d %d\n", id, maxSum, maxLeft + 1, maxRight + 1);
		if(id != t) printf("\n");
	}
	return 0;
}

时间开销如下

呼呼,四种算法总算都实现了。实现过程虽然很受挫,但是很充实的说,结果也很让人愉快,A wonderful day~

HDU1003 Max Sum 最大子序列和的问题【四种算法分析+实现】

时间: 2024-10-14 02:52:12

HDU1003 Max Sum 最大子序列和的问题【四种算法分析+实现】的相关文章

解题报告:hdu1003 Max Sum - 最大连续区间和 - 计算开头和结尾

2017-09-06 21:32:22 writer:pprp 可以作为一个模板 /* @theme: hdu1003 Max Sum @writer:pprp @end:21:26 @declare:连续区间最大和 @data:2017/9/6 */ #include <bits/stdc++.h> using namespace std; int main() { //freopen("in.txt","r",stdin); int cas; cin

HDU1003 Max Sum

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1003 题意:给你一组数字,求出最大的字段和. 思路:这是一个经典的dp题目,定义数组a储存一组数字,a[j]为ji个数,dp[j]表示已j结尾的最大字段和,那么dp[j]=max(dp[j-1]+a[j],dp[j]). 例如: a[]       6   -1   5    4    -7 dp[]     6    5   10  14    7 代码如下: #include <iostream

HDU1003 Max Sum(最大连续子序列和)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1003 简单dp,状态转移方程:sum[i] = max{sum[i-1]+a[i],a[i]}. (sum[i]记录以a[i]为子序列末端的最大连续和.) 对于a[i]这个数字,我们考虑是否将它选入之前连续的序列. 如果选,状态变为sum[i-1]+a[i] ; 如果不选,则从此开始一个新的序列,故和为a[i]. 1 #include<cstdio> 2 int main() 3 { 4 int T,

ACM学习历程—HDU1003 Max Sum(dp &amp;&amp; 最大子序列和)

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 inte

HDU--1003 Max Sum(最大连续子序列和)

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

hdu1003 Max Sum(经典dp )

A - 最大子段和 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u 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 thi

HDU1003 Max Sum 解题报告

目录 题目信息 Problem Description Input Output Sample Input Sample Output 题解 思路 源代码 题目信息 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

HDU1003 Max Sum(求最大字段和)

事实上这连续发表的三篇是一模一样的思路,我就厚颜无耻的再发一篇吧! 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1003 ---------------------------------------------------------------------------------------------------------------------------------------------------------- 欢迎光临天资小屋:

hdu1003 Max Sum【最大连续子序列之和】

题目链接:https://vjudge.net/problem/HDU-1003 题目大意:给出一段序列,求出最大连续子序列之和,以及给出这段子序列的起点和终点. 解题思路:最长连续子序列之和问题其实有很多种求解方式,这里是用时间复杂度为O(n)的动态规划来求解. 思路很清晰,用dp数组来表示前i项的最大连续子序列之和,如果dp[i-1]>=0的话,则dp[i]加上dp[i-1]能够使dp[i]增大:若dp[i-1]<0的话,则重新以dp[i]为起点,起点更新. #include <cs