|
题目:
http://acm.hdu.edu.cn/showproblem.php?pid=1003
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 3178 Accepted Submission(s) : 564
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
算法暂时就不描述了
代码很长,希望能帮忙找找BUG...
总是得到WA
(提交时 getch() 去掉了的.)- #include "stdio.h"
- int main()
- {
- long int max,in,a[3],n=0;
- int i=0,j=0,p,s,e,len;
- int as,ae,bs,be;
- scanf("%ld",&n);
- while(n--){
- a[0]=a[1]=a[2]=-1001;
- j++;
- scanf("%d",&len);
- if(len>0){
- scanf("%ld",&in);
- max=in;
- p=1;
- ae=be=as=bs=s=e=1;
- i=0;
- /*
- *处理开始处的零与负数
- */
- while(in<0 && p<len){
- if(max<in){
- max=in;
- s=e=p;
- }
- scanf("%ld",&in);
- bs++;
- p++;
- }
- if(p>len){goto output;}/*___BAD___BAD___*/
- a[0]=in;
- as=ae=p;
- if(p>=len)goto output;
- scanf("%ld",&in);
- p++;
- while(in>=0 && p<=len){
- a[0]+=in;
- ae=p;
- if(p>=len)goto output;
- scanf("%ld",&in);
- p++;
- }
- if(a[0]>max){
- max=a[0];
- s=as;e=ae;
- }
- a[1]=in;i=1;
- while(1){
- if(p>=len)goto output;
- scanf("%ld",&in);
- p++;
- switch(i){
- case 1:
- if(in<0){
- a[1]+=in;
- }
- else{
- a[2]=in;i=2;bs=be=p;/*调整a[2]的位置*/
- }break;
- case 2:
- if(in>=0){
- a[2]+=in;
- be=p;
- }
- else{
-
- /*调整max*/
- if(max<a[0]){
- max=a[0];s=as;e=ae;
- }
- if(max<a[0]+a[1]+a[2]){
- max=a[0]+a[1]+a[2];
- s=as;e=be;
- }
- if(max<a[2]){
- max=a[2];
- s=bs;e=be;
- }
- /*调整下一个a[0]*/
- if(a[0]+a[1]>0){
- a[0]=a[0]+a[1]+a[2];
- ae=be;/*下一个a[0]*/
- }else{
- a[0]=a[2];
- as=bs;ae=be;
- }
- i=1;
- a[1]=in;
- }break;
- }/*End of switch*/
- }
- }/*End of one case's deal.*/
- output:
- if(max<a[0]){
- max=a[0];
- e=ae;s=as;
- }
- if(max<a[0]+a[1]+a[2]){
- max=a[0]+a[1]+a[2];
- s=as;e=be;
- }
- if(max<a[2]){
- max=a[2];
- s=bs;e=be;
- }
- printf("Case %d:\n%ld %d %d\n",j,max,s,e);
- if(n!=0)printf("\n");
- }/*End of n's loop*/
- getch();
- return 0;
- }
复制代码
[ 本帖最后由 找不了回去的路 于 2007-1-23 18:15 编辑 ] |
|