Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 72615 Accepted Submission(s): 16626
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
算法分析:求最大字段和,d[i]表示已 i 结尾(字段和中包含 i )在 a[1..i] 上的最大和,d[i]=(d[i-1]+a[i]>a[i])?d[i-1]+a[i]:a[i];
max = {d[i],1<=i<=n} ;
#include<iostream>
#define N 100010
using namespace std;
int a[N],d[N];
int main()
{
int test,n,i,max,k,f,e;
cin>>test;
k=;
while(test--)
{
cin>>n;
for(i=;i<=n;i++)
cin>>a[i];
d[]=a[];
for(i=;i<=n;i++)
{
if(d[i-]<) d[i]=a[i];
else d[i]=d[i-]+a[i];
}
max=d[];e=;
for(i=;i<=n;i++)
{
if(max<d[i])
{
max=d[i];e=i;
}
}
int t=;
f=e;
for(i=e;i>;i--)
{
t=t+a[i];
if(t==max) f=i;
}
cout<<"Case "<<k++<<":"<<endl<<max<<" "<<f<<" "<<e<<endl;
if(test) cout<<endl;
}
return ;
}
改进后的只处理最大和不处理位置
#include<cstdio>
int main()
{
int n,test,ans,t,a,i;
scanf("%d",&test);
while(test--)
{
scanf("%d",&n);
scanf("%d",&a);
ans=t=a;
for(i=;i<n;i++)
{
scanf("%d",&a);
if(t<) t=a;
else t=t+a;
if(ans<t) ans=t;
}
printf("%d\n",ans);
}
return ;
}
#include <bits/stdc++.h>
using namespace std; int main()
{
int T;
scanf("%d", &T); int N;
int a;
int ans;
int sum;
int i;
int bg, ed;//起始,结束
int bg2;
int cas = ; while (T--) {
scanf("%d", &N); ans = -;//
sum = ;//
bg2 = ;//默认起始位置
for (i = ; i < N; ++i) {
scanf("%d", &a); sum = sum + a;
if (sum > ans) {
ans = sum;
bg = bg2;
ed = i;
}
if (sum < ) {//< 0 那么这段到此为止吧
sum = ;//
bg2 = i + ;//更新起始位置
}
} printf("Case %d:\n", ++cas);
printf("%d %d %d\n", ans, bg + , ed + );
if (T > ) {
printf("\n");
}
}
return ;
}
这个和上面的相比写法容易理解些
#include <bits/stdc++.h>
using namespace std; int main()
{
int T;
scanf("%d", &T); int N;
int a;
int ans;
int sum;
int i;
int bg, ed;//起始,结束
int bg2;
int cas = ; while (T--) {
scanf("%d", &N); scanf("%d", &a);
ans = a;
sum = a;
bg = , ed = ;
bg2 = ; for (i = ; i < N; ++i) {
scanf("%d", &a); if (sum <= ) {//从样例2 看,这里要<,但是<= 也可以,只要找到一个最大的子串就可以
sum = a;
bg2 = i;
} else {
sum = sum + a;
} if (sum >= ans) {//这里> 和>= 都可以
ans = sum;
bg = bg2, ed = i;
}
} printf("Case %d:\n", ++cas);
printf("%d %d %d\n", ans, bg + , ed + );
if (T > ) {
printf("\n");
}
}
return ;
}