hdu 1231, maximum consecutive sum of integers, finding the boundaries, possibly all negative, C++

the algorithm of three version below is essentially the same, namely, Kadane’s algorithm, which is of O(n) complexity. https://en.wikipedia.org/wiki/Maximum_subarray_problem

the evolution of the implementations is to remove redundancy and do what is really needed, the side effect of doing so is becoming more efficient.

IMHO, version 1.0.2 is well commented which shows the guidelines of efficient bookkeeping of boundaries, first and last can also be easily changed to first_iter and last_iter to print the whole subarray if needed.

// version 1.0.0, a coordinate array, a traversing to find the first element

#include <cstdio>
#include <algorithm>

#define MAXSIZE 10005

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int N,i,tmp,*p;
    int nums[MAXSIZE]={-1}, dp[MAXSIZE]={0};
    while(scanf("%d",&N)==1 && N>0) {
        for(i=1;i<=N;++i) { scanf("%d",&nums[i]); }
        for(i=1;i<=N;++i) {
            tmp=nums[i]+(dp[i-1]>0?dp[i-1]:0);
            dp[i]=tmp>0?tmp:0;
            //dp[i]=std:max(0,nums[i]+std::max(dp[i-1],0));
        }
        p=std::max_element(dp,dp+N+1);
        if(p==dp) {
            if(nums==std::max_element(nums,nums+N+1)) { i=1,tmp=N; }
            else {
                for(i=0;i<=N && nums[++i]<0;) {}
                for(tmp=i;nums[++tmp]==0;) {} --tmp;
            }
        }
        else {
            for(tmp=i=p-dp;i>0 && dp[--i]>0;) {}
            for(;i>0 && nums[i]==0 && dp[--i]==0;) {} ++i;
        }
        printf("%d %d %d\n",*p,nums[i],nums[tmp]);
    }
    return 0;
}

// version 1.0.1, no coordinate array, modifying the data, a traversing to find first element

#include <cstdio>
#include <algorithm>

#define MAXSIZE 10005

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int N,i,j,tmp,last,sum;
    int nums[MAXSIZE]={-1};
    while(scanf("%d",&N)==1 && N>0) {
        for(i=1;i<=N;++i) { scanf("%d",&nums[i]); }
        for(sum=-1,last=nums[N],j=0, i=1;i<=N;++i) {
            tmp=nums[i]+(nums[i-1]>0?nums[i-1]:0);
            if(tmp>=0) {
                if(tmp>sum) { sum=tmp; last=nums[i]; j=i; }
                nums[i]=tmp;
            }
        }
        if(sum==-1) ++sum;
        else for(;j>0 && nums[--j]>=0;) {}
        printf("%d %d %d\n",sum,nums[j+1],last);
    }
    return 0;
}

// version 1.0.2, no coordinate array, not modify data, no extra traversing to find boundary element

#include <cstdio>
#include <algorithm>

#define MAXSIZE 10005

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    // prev -- maxsum ending here, sum -- maxsum so far, res -- result
    int N,i,first,last,tmp,sum,res,prev;
    int nums[MAXSIZE];
    while(scanf("%d",&N)==1 && N>0) {
        for(i=0;i<N;++i) { scanf("%d",&nums[i]); }
        for(res=prev=sum=-1,first=nums[0],last=nums[N-1], i=0;i<N;++i) {
            if(prev<0) {
                if(nums[i]>=0) {
                    // prev start increasing, update candidate of first -- tmp
                    tmp=prev=nums[i];
                    // update candidate of result -- sum
                    if(prev>sum) { sum=prev; }
                }
            }
            else {
                prev+=nums[i];
                // prev stop increasing, update first, last, res
                if(nums[i]<=0) { if(sum>res) { res=sum; first=tmp; last=nums[i-1]; } }
                // update candidate of result -- sum
                else if(prev>sum) { sum=prev; }
            }
        }
        // update first, last, res, -- only if partial sum remain increasing
        if(sum>res) { res=sum; first=tmp; last=nums[i-1]; }
        // all negative
        if(res==-1) ++res;
        printf("%d %d %d\n",res,first,last);
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-09-30 16:28:54

hdu 1231, maximum consecutive sum of integers, finding the boundaries, possibly all negative, C++的相关文章

HDU 1977 Consecutive sum II(数学)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1977 Problem Description Consecutive sum come again. Are you ready? Go ~~ 1    = 0 + 1 2+3+4    = 1 + 8 5+6+7+8+9  = 8 + 27 - You can see the consecutive sum can be representing like that. The nth line w

Maximum Subsequence Sum - 最大子列和问题_C语言实现

第一次写这方面的blog.自己也是初次接触相关知识,写的有不妥的地方十分欢迎大家指正~ 这是浙大PAT上的一道算法题(据说是浙大04年研究生复试题),题目是这样的: Maximum Subsequence Sum Given a sequence of KK integers { N_1N?1??, N_2N?2??, ..., N_KN?K?? }. A continuous subsequence is defined to be { N_iN?i??, N_{i+1}N?i+1??, ..

hdu 4267 A Simple Problem with Integers

题目链接:hdu 4267 A Simple Problem with Integers 类似于题目:hdu 1556 Color the ball 的技巧实现树状数组的段更新点查询. 由于该题对于段的更新并不是连续的,从而可以构造多个树状数组.因为$k \in [1,10] $,从而可以把更新划分为如下类型: 1,2,3,4,5... ------------- 1,3,5,7,9... 2,4,6,8,10... ------------- 1,4,7,10,13... 2,5,8,11,1

HDU 1231 最大连续子序列 DP题解

典型的DP题目,增加一个额外要求,输出子序列的开始和结尾的数值. 增加一个记录方法,nothing special. 记录最终ans的时候,同时记录开始和结尾下标: 更新当前最大值sum的时候,更新开始节点. const int MAX_N = 10001; long long arr[MAX_N]; int N, sta, end; long long getMaxSubs() { long long sum = 0, ans = LLONG_MIN; int ts = 0; for (int

[ACM] hdu 1231 最大连续子序列 (动规复习)

最大连续子序列 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 17687    Accepted Submission(s): 7828 Problem Description 给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j

HDU 6058 Kanade&#39;s sum —— 2017 Multi-University Training 3

Kanade's sum Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2512    Accepted Submission(s): 1045 Problem Description Give you an array A[1..n]of length n. Let f(l,r,k) be the k-th largest eleme

Maximum Subsequence Sum 最大子序列和的进击之路

本文解决最大子序列和问题,有两个题目组成,第二个题目比第一个要求多一些(其实就是要求输出子序列首尾元素). 01-复杂度1 最大子列和问题   (20分) 给定KK个整数组成的序列{ N1??, N2??, ..., NK?? },"连续子列"被定义为{ N?i??, Ni+1 ..., Nj },其中 1≤i≤j≤K."最大子列和"则被定义为所有连续子列元素的和中最大者.例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4,

LintCode Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. Example Given the below binary tree: 1 / 2 3 return 6. For this problem we need to think about the problem in this way. Now we want the largest sum of

pat1007. Maximum Subsequence Sum (25)

1007. Maximum Subsequence Sum (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The