码迷,mamicode.com
首页 > 其他好文 > 详细

3查找最长和的数字串

时间:2016-05-13 02:35:04      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:

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.<br>
 

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).<br>
 

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.<br>
 

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

思路:给出一串数字,求出他的子字串和最大是多少。

累加,一直到他之前的数小于零就算是断串,再从断串处开始搜索,继续以上步骤。

例如 5 6 -1 4 5 -7

6 5 9 14 7 此时14就是最大值 结果就为14 1 4.

三个步骤:

1,初始化,将now before max赋值为第一个数,x动态的指针,最终付给start end是结束地址

2,判断是否断串

2.1 假如断串(判断是否断的条件是 now > now + before),从断串处重新开始搜索此时before = now,x=i;

2.2 不断串,累加,before = before + now;

3,最大值 如果before > max 则max = before,并且 start = x;end = i;

代码:

#include<iostream> #include<stdio.h> using namespace std; int main() {     int t,n,now,before,start,eend,flot = 1,x,mmax;     scanf("%d",&t);     while(t--)     {         scanf("%d",&n);         for(int i=1;i<=n;++i)         {             scanf("%d",&now);             if(i==1)//初始化             {                 before = now;                 mmax = now;                 x = 1;//动态指针,用来预存初始位置,最后赋予start                 start = 1;//初始位置                 eend = 1;//结束位置             }             else//开始计算             {                 if(now > now + before)//断串的情况                 {                     before = now;//从此处开始搜索                     x = i;//初始位置变化啦                 }                 else                     before = before + now;//没有断的话,一直进行累加                 if(before > mmax)//比之前的before大了                 {                     start = x;                     eend = i;                     mmax = before;                 }             }         }         printf("Case %d:\n%d %d %d\n",flot++,mmax,start,eend);         //printf("Case %d:\n%d %d %d\n",flot++,mmax,start,eend);         if(t)             printf("\n");     }     return 0; }

3查找最长和的数字串

标签:

原文地址:http://blog.csdn.net/mrango/article/details/51345900

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!