博客
关于我
洛谷 1115 最大子段和、HDU 1003 Max Sum(最大字段和问题)
阅读量:328 次
发布时间:2019-03-04

本文共 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 4

Case 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;}

转载地址:http://pcnh.baihongyu.com/

你可能感兴趣的文章
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>
mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>