# 最大连续字段和

HDU1231

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int MAX_N=100005;
#define inf 1<<23
typedef long long ll;
typedef long long LL;
int a[MAX_N];
int n;
int s,e;//记录开始和结束
void text()
{
int maxValue=0;
int thisMaxValue=0;
for(int i=0;i<n;i++)
{
thisMaxValue+=a[i];
if(thisMaxValue>0)
{
maxValue=thisMaxValue>maxValue?thisMaxValue:maxValue;
}
else
{
thisMaxValue=0;
}
}
printf("%d\n",maxValue);
}
int main()
{
while(scanf("%d",&n)&&n)
{
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
text();
}
return 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.
InputThe 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).
OutputFor 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<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
using namespace std;
const int MAX_N=100010;
typedef long long ll;
typedef long long LL;
int a[MAX_N];
int n;

void  text(int &res,int &s,int &e)
{
int maxValue=-(1<<30);
int thisMaxValue=0;
int k=1;
for(int i=0; i<n; i++)
{
thisMaxValue+=a[i];
//cout<< thisMaxValue <<endl;

if(thisMaxValue>maxValue)
{
maxValue=thisMaxValue;
s=k;
e=i+1;
}
if(thisMaxValue<0)
{
thisMaxValue=0;
k=i+2;
}
}
res=maxValue;
}

int main()
{
int t;
int s,e;
int res;
scanf("%d",&t);

for(int j=1; j<=t; j++)
{
s=0;
e=0;
memset(a,0,sizeof(a));
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
text(res,s,e);
if(j!=t)
{
printf("Case %d:\n",j);
printf("%d %d %d\n\n",res,s,e);
}
else
{
printf("Case %d:\n",j);
printf("%d %d %d\n",res,s,e);
}
}

return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120