HDU 1003 Max Sum
来源:互联网 发布:大神小的知错了微盘 编辑:程序博客网 时间:2024/06/06 15:54
简单dp入门
其实感觉这题贪心可写,分治可写
题目:
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
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
思路:简单的dp,然而我开的数组明显比别人多一个,甚至有些人没开数组。。
我的想法是先开一个数组d[maxn] 保存以i为结尾的最大的连续和的值,而sti[i]保存这些值以哪一个下标为开始。
temp 是当前下标为i的值
故有d[i] = max(temp, temp + d[i-1]); 当temp值比较大时,sti[i] = i,另外一种情况时, sti[i] = sti[i-1]
代码:
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;#define maxn 100005#define inf 0x3f3f3f3fint d[maxn];int sti[maxn];int main(){ //freopen("D://in.txt","r",stdin); int t; scanf("%d",&t); for(int kase = 1; kase <= t; kase ++) { int n; scanf("%d",&n); int temp; scanf("%d",&temp); d[0] = temp; for(int i = 1; i < n ; i++) { scanf("%d",&temp); d[i] = max(d[i-1] + temp, temp); if(d[i-1] + temp <= temp) sti[i] = i; else sti[i] = sti[i-1]; } int ans = -inf; int ansj = -1; int ansi = -1; for(int i = 0; i < n ; i++) { if(ans < d[i]) { ans = d[i]; ansj = i; ansi = sti[i]; } } if(kase != 1) printf("\n"); printf("Case %d:\n",kase); printf("%d %d %d\n",ans,ansi+1,ansj+1); } return 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
- 管理员命令下pip错误unable to create process using的解决方法
- sqoop导出hive数据到mysql错误: Can't parse input data java.util.NoSuchElementException解决办法
- 反射机制的运用
- 超过单行多余的显示...与显示多行超出的显示...
- 集合框架-产生10个1-20之间的随机数,要求随机数不能重复
- HDU 1003 Max Sum
- 辨清DOM元素的特性与属性
- mysql的启动相关操作
- Chrome浏览器前端开发常用的插件和扩展程序
- MySQL基础知识七
- Elimination Game
- retrofit Json解析
- 函数在一个字符串中进行搜索,查找所有在一个给定字符集合中出现的字符,函数原型:char *find_char( char const *source, char const *chars);
- 欢迎使用CSDN-markdown编辑器