hdu=1003 Max Sum
来源:互联网 发布:python接收命令行参数 编辑:程序博客网 时间:2024/06/15 11:00
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
题目大意:输入一个整数t,接下来有t组测试数据,每一组输入一个数n,接着输入n个整数,计算并输出出这n个整数的最大和、开始位置和结束位置。
以 6 -7 5 -1 4为例,以6为起始位置时,6+(-7)=-1,第三项5加上前两项和(-1)之后变小,不如以5为起始位置。
算法:用sum存入前n项和,如果加到第x项时sum<0,初始化sum并以x+1位置为起始位置累加sum和。计算过程中比较sum与max的大小并更新max值,更新max值的同时保存起始位置与结束位置。
AC代码
#include <stdio.h>#include <string.h>int a[100010];int main(){ int t,i,k,n,sum,max,start = 0,end = 0,temp; scanf("%d",&t); for(k=1;k<=t;k++){ memset(a, 0, sizeof(a)); sum=0;temp=0;max=-1010;// 初始化数据 scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++){ sum=sum+a[i];//累加前n项和 if(sum>max){ start=temp; max=sum; end=i; } //sum>max时,更新max值同时保存起始位置和结束位置 if(sum<0) { sum=0; temp=i+1; } //sum<0时初始化sum并以下一项为起始位置 } printf("Case %d:\n%d %d %d\n",k,max,start+1,end+1); if(k!=t) printf("\n"); }}
ps. 两个if的语句不能调换位置,第一次写的时候wa了一次。如果调换位置在全部输入负数时会出错。
阅读全文
0 0
- hdu=1003 Max Sum
- HDU 1003 Max Sum
- hdu 1003 Max Sum
- hdu 1003 Max Sum
- HDU-1003 max sum
- HDU 1003 - Max Sum
- HDU 1003 Max Sum
- hdu 1003 Max Sum
- HDU 1003 Max Sum
- HDU 1003 Max Sum
- hdu 1003 max sum
- HDU 1003 Max Sum
- hdu 1003 Max Sum
- HDU 1003 Max Sum
- hdu 1003 Max Sum
- HDU 1003 Max Sum
- Hdu 1003 - Max Sum
- HDU-1003-Max Sum
- 第二课断链隐藏驱动
- Java笔记:类和对象
- C/C++ 二维数组与指针
- 2017-08-16学习随笔之Struts1-2
- 对称密码 之 分组密码与数据加密标准
- hdu=1003 Max Sum
- Android 原生系统,手机rom下载网站
- tiaotiaoxuanxuan
- POJ 3687 Labeling Balls (逆向拓扑排序)
- 二十三种设计模式之解释器模式
- HDU-1255 覆盖的面积(线段树扫描线模板+离散化+加点修改题)
- 浅析TCP中时间戳选项timestamp
- C语言编写简易通讯录
- ubuntu16.0.4环境下搭建DeepNet深度学习框架