PAT (Advanced Level) Practise 1007. Maximum Subsequence Sum (25)

来源:互联网 发布:数据库逻辑完整性 编辑:程序博客网 时间:2024/06/16 14:09

1007. Maximum Subsequence Sum (25)

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 Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:
10-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
题解:
这道题是一道典型的求最大连续子序列和的题目,只不过题目绕了个弯儿,还要给出相应的子序列的第一个和最后一个数字,只要进行相应的处理即可。
代码:
#include <cstdio>#include <algorithm>using namespace std;const int maxn=10000+10;int a[maxn],dp[maxn],s[maxn]={0};int main(){    int n;    scanf("%d",&n);    for(int i=0;i<n;i++) scanf("%d",&a[i]);    int ok=0;    for(int i=0;i<n;i++){        if(a[i]>=0) ok=1;    }    if(!ok){        printf("0 %d %d\n",a[0],a[n-1]);        return 0;    }    dp[0]=a[0];    for(int i=1;i<n;i++){        if(dp[i-1]+a[i]>a[i]){            dp[i]=dp[i-1]+a[i];            s[i]=s[i-1];        }        else{            dp[i]=a[i];            s[i]=i;        }    }    int k=0;    for(int i=1;i<n;i++){        if(dp[i]>dp[k]) k=i;    }    printf("%d %d %d\n",dp[k],a[s[k]],a[k]);    return 0;}


阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 医保卡丢了怎么办又记不住卡号 住院发票丢了医保不给报销怎么办 住院期间被医院丢失了医保卡怎么办 大学时的医保卡毕业后丢了怎么办 用身份证注册的移动卡丢了怎么办 用别人身份证办的卡丢了怎么办 济南医保卡挂失后又找到了怎么办 单位没有给办理医保卡的老人怎么办 单位办的医保卡丢了怎么办 北京退休人员医保卡丢了怎么办 普通发票联丢了医保给报销怎么办 手机买好高铁票身份证丢了怎么办 买了高铁票身份证丢了怎么办 小米手机手电简打开不亮了怎么办 华为p7手机显示屏不亮了怎么办 红米手机3x屏幕不灵怎么办? 乐视1s手机字库坏了怎么办 三星c7手机左右两按钮不亮怎么办 手机摔了一屏碎了下黑屏了怎么办 三星手机摔了一下黑屏了怎么办 行驶证一年扣分超过50分怎么办 朋友去广西传销现在骗我怎么办 行驶证忘带交警查住了怎么办 行驶证正本丢了副本在怎么办 在杭州驾照12分扣完了怎么办 驾照审验期过了40天了怎么办 自己的车借给别人撞死了人怎么办 无证驾驶报别人驾驶证被扣车怎么办 交了强制险但驾驶证过期了怎么办 考驾照科目一身份证掉了怎么办 驾照科目二考试身份证丢了怎么办 身份证遗失又要参加考试怎么办啊 驾驶本到期换本有扣分怎么办 b2驾驶证六年到期有扣分怎么办 驾考有效期是几年过期了怎么办? 驾考要过期了科四补考没过怎么办 驾驶证过期了可副业丢了怎么办 外地人北京驾驶本到期换本怎么办 报考驾照时电话号码填错了怎么办 报考驾照时电话填错了怎么办 邢台开三轮车驾证扣12分怎么办