hdu1003 Max Sum (求连续的和最大的自链
2017-04-24 10:59
288 查看
Max SumTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 242181 Accepted Submission(s): 57180Problem DescriptionGiven a sequence a[1],a[2],a[3]......a, 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. InputThe 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). OutputFor 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 Input25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5 Sample OutputCase 1:14 1 4Case 2:7 1 6题意:t组数据,长度为n的字符串,找出一段连续且和最大的字符串#include<stdio.h>#include<iostream>#include<algorithm>using namespace std;const int inf=0x3f3f3f3f;int main(){int t;scanf("%d",&t);int k=t;while(t--){int n;scanf("%d",&n);int maxx=-inf,sum=0;int x=1,y=0,temp=1;//temp用来标记起点for(int i=0; i<n; i++){int a;scanf("%d",&a);sum+=a;if(sum>maxx)//两个if判断不能换位置,例5 -1 -2 -3 -4 -5//这样会提前改变sum和temp的值,从而错误{maxx=sum;x=temp;y=i+1;}if(sum<0){sum=0;temp=i+2;//如果不用temp标记起点,直接用x的话例:5 -1 -2 -3 -4 -5//x会一直加下去,输出就会出错//x=i+1;}}printf("Case %d:\n%d %d %d\n",k-t,maxx,x,y);if(t!=0)printf("\n");}return 0;}
这个是错误的代码,我考虑一下我错哪了#include<stdio.h>#include<iostream>#include<algorithm>using namespace std;const int inf=0x3f3f3f3f;int main(){int t;scanf("%d",&t);while(t--){int n;scanf("%d",&n);int maxx=-inf,sum=0;int x=0,y=0,temp=1;//这种代码,有特别多的弊端,//值全为0时,maxbc0dx,x,y都不对//还有只要sum>0都能进入那个循环,y就会一直加,也是错的for(int i=0;i<n;i++){int a;scanf("%d",&a);sum+=a;if(sum<0){x=i+1;y=i+1;sum=0;}else{maxx=max(maxx,sum);y+=1;}}}}
相关文章推荐
- Max Sum 最大连续和的子序列 HDU 1003 (一维序列DP)
- HDU 1003 Max Sum——dp求最大连续和O(n)
- Max Sum 最大连续和的子序列 HDU 1003 (一维序列DP)
- HDU1003 Max Sum(最大连续子序和、贪心、DP)
- HDU-1003 Max Sum (线性dp 最大连续和)
- Max Sum 最大连续和的子序列 HDU 1003 (一维序列DP)
- HDU-1003 Max Sum(最大连续子段和)
- HDU 1003 Max Sum 最大连续上升和
- HDU 1003 MAX SUM 最大连续子段和DP
- HDU 1003 Max Sum 最大连续和 分治法
- Max Sum 最大连续和的子序列 HDU 1003 (一维序列DP)
- hdu(1003)——Max Sum(最大连续子段和)
- HDU - 1003 Max Sum (最大连续和)
- Max Sum(hdu1003最大连续子串和+分治法)
- HDU - 1003 Max Sum (最大连续和)
- HDU 1003 Max Sum【最大连续和】
- Max Sum 最大连续和的子序列 HDU 1003 (一维序列DP)
- hdu1003——max sum;(最大连续字串和)
- HDU - 1003 Max Sum(最大连续子段和)
- HDU 1003 Max Sum(最大连续子段和)