hdu1003 Max Sum(经典dp )

时间:2021-07-09 17:06:00
 
A - 最大子段和

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

 

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 <cstdio>
int main()
{
int T,k, R, L, Max, sum, t, total=, n;
scanf("%d", &T);
while(T--)
{
sum = Max =-; //足够小就好
scanf("%d", &n);
for(int i=; i<=n; i++)
{
scanf("%d", &t);
if (sum<)
{
sum = t, k = i;
}
else
sum += t;
if (Max < sum) Max = sum, L = k, R = i; //L R分别为初始和结束位置
}
printf("Case %d:\n", total++);
printf("%d %d %d\n", Max, L, R );
if (T) printf("\n");
}
return ;
}
#include<iostream>
using namespace std;
int a[],b[];
int main()
{
int n,T,s,t,max,total,k=;
cin>>T;
while(T--)
{
cin>>n;
for(int i=; i<=n; i++)
cin>>a[i];
b[]=a[];
for(int i=; i<=n; i++)
{
if(b[i-]<)
b[i]=a[i];
else
b[i]=b[i-]+a[i];
}
max=b[];
s=;
for(int i=; i<=n; i++)
{
if(b[i]>max)
{
max=b[i];
s=i;
}
}
t=s;
total=;
for(int i=s; i>=; i--)
{
total+=a[i];
if(total==max) t=i;
}
cout<<"Case "<<k++<<":"<<endl;
cout<<max<<" "<<t<<" "<<s<<endl;
if(T) cout<<endl;
}
}