标签:
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
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; }
标签:
原文地址:http://blog.csdn.net/mrango/article/details/51345900