hud 1003 最大连续子序列和
来源:互联网 发布:政府应对网络舆情 编辑:程序博客网 时间:2024/04/18 04:56
题目链接点击打开链接
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 189843 Accepted Submission(s): 44213
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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
Sample Output
Case 1:14 1 4Case 2:7 1 6
设置几个参数,start表示最大子序列的开始点,end 表示结束点,t表示一段连续子序列的和,k表示这段连续子序列的起点,result用来保存最终结果,因为每个数字最小为-1000,所以result初始值比-1000小即可。
将i从0到n遍历一遍,如果t的值大于result的值,则更新result,同时start的值更新为k(此时可能start的值并没有改变),end的值更新为i。
如果t小于0,则将t重新初始化为0,k更新为i + 1,因为如果最后结果是后面的某个子序列,则这个子序列的起点肯定是该点后面某个非负值。此时后面再遇到t大于result的情况start的值更新后则会发生变化。
输出需要注意的是每两个样例之间要空一行,最后一个样例后面不需要单独的空行
#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>using namespace std;const int maxn = 100000 + 10;int a[maxn];int main(){ int T;scanf("%d", &T); int coun = 1; while(T--){ int n;scanf("%d", &n); int t = 0; int result = -2000; int start, end, k; start = end = k = 0; for(int i = 0; i < n; i++){ scanf("%d", &a[i]); t += a[i]; if(t > result){ result = t; start = k; end = i; } if(t < 0){ t = 0; k = i + 1; } } printf("Case %d:\n%d %d %d\n", coun++, result, start + 1, end + 1); if(T != 0) printf("\n"); } return 0;}
0 0
- hud 1003 最大连续子序列和
- hdu 1003 最大连续子序列和
- 连续子序列最大和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- 最大连续子序列和
- SSL 协议通讯建立过程
- mysql 数据插入优化方法
- 嵌入式程序地址解析
- 关于STM32 PB3 PB4 如何设置成普通GPIO的配置
- 13.c/c++程序员面试宝典-宏定义
- hud 1003 最大连续子序列和
- IBM Bluemix 是什么?
- 适配器(Adapter)模式
- ios 开发关于NSMutableAttributedString的使用
- shell中的几个特殊变量
- 【ios开发】如何判断当前网络连接状态(网络是否正常)
- java中length,length(),size()区别
- SVN tree conflict
- 运行项目编译报错