首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求大神指教,这程序是如何个思想

2012-06-11 
求大神指教,这程序是怎么个思想?Problem DescriptionGiven a sequence a[1],a[2],a[3]......a[n], your jo

求大神指教,这程序是怎么个思想?
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

代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
  int i,t;
  scanf("%d",&t);
  for (i=1; i<=t; i++)
  {
  int j,n,max=-1001,sum=0,tmp=1,*a;
  int first=0,last=0;
  scanf("%d",&n);
  a = (int *)malloc(n*sizeof(int));
  for (j=0; j<n; j++)
  {
  scanf("%d",a+j);
  sum += a[j];
  if (sum>max)
  {
  max = sum;
  first = tmp;
  last = j+1;
  }
  if (sum<0)
  {
  sum = 0;
  tmp = j+2;
  }
  }
  printf("Case %d:\n%d %d %d\n",i,max,first,last);
  if (i!=t)
  printf("\n");
  free(a); a = NULL;
  }
  return 0;
}


[解决办法]
假设a(k)到a(j)的和最大,那么a(1)到a(k-1)一定是负数,否则a(i)到a(j)的和就大于a(k)到a(j)的和
因此可以把和是负数的地方看成断点然后重新开始累加,
最后记录整个累加过程的最大值就好

热点排行