【算法】HDOJ-1003 Max Sum
来源:互联网 发布:qq无限加人软件 编辑:程序博客网 时间:2024/06/08 09:38
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 101585 Accepted Submission(s): 23360
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
Author
Ignatius.L
Code:
提交时注意数据规模,我前几次提交数组只定义了1001,全部WA,后来发现原题中规定1<=N<=100000,so把数组大小改为了100001。
#include <stdio.h>
using namespace std;
int main(){ int f[100001]; int T,N,i,start,end,count=1,sum,Max,k; scanf("%d",&T); while(T--){ sum=0,Max=-99999; k=1,start=1;end=1; scanf("%d",&N); for(i=1;i<=N;i++){ scanf("%d",&f[i]); sum+=f[i]; if(sum>Max){ Max=sum; start=k; end=i; } if(sum<0) { k=i+1; sum=0; } } printf("Case %d:\n",count++); printf("%d %d %d\n",Max,start,end); if(T!=0) printf("\n"); } return 0;}
第二种方法运用动态规划,动态转移方程为f[i]=max{f[i-1]+f[i],f[i]},由此得出程序:
#include <stdio.h>using namespace std;int main(){ int f[100001]; int start,end; int i,T,N,count=1; scanf("%d",&T); while(T--){ int q[100001]; q[1]=1; start=1; end=1; scanf("%d",&N); for(i=1;i<=N;i++){ scanf("%d",&f[i]); if(i==1) continue; if(f[i-1]+f[i]>=f[i]) {f[i]=f[i-1]+f[i];q[i]=0;} else q[i]=1; if(f[i]>f[end]) {end=i;} } for(i=end;i>0;i--) if(q[i]==1) {start=i;break;} printf("Case %d:\n",count++); printf("%d %d %d\n",f[end],start,end); if(T!=0) printf("\n"); } return 0;}
- 【算法】HDOJ-1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- hdoj 1003 Max Sum
- HDOJ 1003 Max Sum
- hdoj 1003Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ--1003Max Sum
- hdoj 1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- HDOJ 1003 Max Sum
- hdoj 1003 Max Sum
- HDOJ Max Sum 1003
- 【HDOJ 1003】 Max Sum
- VIM 寄存器
- Java乔晓松-oracle 10G的安装向导
- 每个人都有话要说
- 2012百度校园招聘(笔试,一面,二面)
- cut命令学习
- 【算法】HDOJ-1003 Max Sum
- innodb中的REDO解析
- ※※Java调用Runtime.exec()要注意的问题
- yii --memcached缓存的配置
- 配置PHP+mssql环境的一些常见问题及解决方案
- 制作分享按钮
- php下载文件
- 从UIView的子类中推入视图控制器
- linux C经典面试题五