【思维】poj1003 Max Sum
2017-05-03 16:24
253 查看
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 242921 Accepted Submission(s): 57358
Problem Description
Given 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.
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
Recommend
We have carefully selected several similar problems for you: 1176 1087 1069 2084 1058
题意:找一个连续的最长子序列使得区间和最大;
思路:这道题在2017河工大校赛中出现过,相比本题不需要输出区间的起始位置和终止位置;当时没有A出,解题思路都是一样的;正着找一遍,反者着一边;WA了好几次是因为初始化的问题;
代码:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=100005; const int inf=0x3f3f3f3f; struct p { int s,t,c; }e[maxn]; int a[maxn]; bool cmp(p e1,p e2) { if(e1.c!=e2.c) return e1.c>e2.c; else return e1.s<e2.s; } int main() { int T,t=0; scanf("%d",&T); while(T--) { t++; int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); memset(e,-0x3f,sizeof(e)); int sum=0,k=0; e[k].s=0; int maxx=-inf; for(int i=0;i<n;i++) { sum+=a[i]; if(sum>=maxx) { maxx=sum; e[k].t=i; e[k].c=sum; } else if(sum<0) { sum=0; e[++k].s=i+1; } } k++; e[k].t=n-1,sum=0; for(int i=n-1;i>=0;i--) { sum+=a[i]; if(sum>=maxx) { maxx=sum; e[k].s=i; e[k].c=sum; } else if(sum<0) { sum=0; e[++k].t=i-1; } } sort(e,e+k+1,cmp); //for(int i=0;i<=k;i++) //printf("%d %d %d\n",e[i].s,e[i].t,e[i].c); printf("Case %d:\n%d %d %d\n",t,e[0].c,e[0].s+1,e[0].t+1); if(T>=1) printf("\n"); } return 0; }
相关文章推荐
- A - Max Sum HDU - 1003 (dp)
- Max Sum HDU - 1003 求最大和
- HDU 1003 Max Sum && HDU 1231 最大连续子序列 (DP)
- hdu1003 Max_Sum
- Max Sum hd 1003
- HDU 1003 Max Sum DP .
- poj2479——Maxnum sum
- 杭电 HDU OJ Max Sum ID1003 AC
- HDU 1003 Max Sum + 单调队列优化dp解法
- HDU.1003【max-sum】---16.2.3
- POJ 3415 Max Sum of Max-K-sub-sequence (线段树+dp思想)
- HDU 1003 Max Sum + 单调队列优化dp解法
- (step3.2.1)hdu 1003(Max Sum——简单DP)
- hdu 1003 max sum #最大字段和
- E - Max Sum HDU - 1003
- 杭电1003 Max Sum TLE
- hdu 1003 Max Sum
- poj 1844 Sum ( 数学思维 )
- 最大子段和 hdu 1003 max sum ACM的开始
- A - Max Sum HDU - 1003