
洛谷 1115 最大子段和、HDU 1003 Max Sum(最大字段和问题)
发布日期:2021-05-07 06:20:45
浏览次数:14
分类:精选文章
本文共 1888 字,大约阅读时间需要 6 分钟。
洛谷 1115 最大子段和
题目描述 给出一段序列,选出其中连续且非空的一段使得这段和最大。 输入输出格式 输入格式: 第一行是一个正整数N,表示了序列的长度。 第二行包含N个绝对值不大于10000的整数Ai,描述了这段序列。 输出格式: 一个整数,为最大的子段和是多少。子段的最小长度为1。#include#include using namespace std;int n, maxx, sum, t;int main(){ cin>>n; cin>>t; maxx=t; sum=t; for (int i=2; i<=n; i++){ cin>>t; sum=sum>0?sum:0; sum+=t; maxx=sum>maxx?sum:maxx; } printf("%d", maxx); return 0;}
HDU 1003 Max Sum
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 4Case 2:
7 1 6#include#include #include #include #include using namespace std;int main(){ int T, n; scanf("%d", &T); for (int k=1; k<=T; k++){ scanf("%d", &n); int t; scanf("%d", &t); int begin=1, end=1, sum=t, maxx=t, begint=1, endt=1; for (int i=2; i<=n; i++){ scanf("%d", &t); if (sum<0){ sum=0; begint=i; endt=i; } sum+=t; if (sum>maxx){ endt=i; begin=begint; end=endt; maxx=sum; } } printf("Case %d:\n", k); printf("%d %d %d\n", maxx, begin, end); if (k!=T) printf("\n"); } return 0;}
发表评论
最新留言
很好
[***.229.124.182]2025年04月10日 20时26分07秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
简单工厂模式
2019-03-06
代理模式
2019-03-06
Js中Currying的应用
2019-03-06
长按键入
2019-03-06
Vuex和普通全局对象
2019-03-06
上升下降字符串
2019-03-06
JavaScript中的链式调用
2019-03-06
day-04-列表
2019-03-06
day-13-匿名函数-内置函数2-闭包
2019-03-06
Linux 磁盘管理(df fu fdisk mkfs mount)
2019-03-06
力扣125. 验证回文串-C语言实现-简单题
2019-03-06
空间向量
2019-03-06
第一类曲面积分
2019-03-06
常数项级数
2019-03-06
Mybatis的介绍和基本使用
2019-03-06
Idea使用tool window中的persistence功能一键生成数据库实体
2019-03-06
Redis简介(数据结构,哨兵、集群和SpringDataRedis)
2019-03-06
jar包破解Idea
2019-03-06
MySQL锁机制
2019-03-06
软件设计模式修炼 -- 模板方法模式
2019-03-06