hdu1003 Max Sum(经典dp 一)

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} ;
View Code
 1 #include<iostream>
2 #define N 100010
3 using namespace std;
4 int a[N],d[N];
5 int main()
6 {
7 int test,n,i,max,k,f,e;
8 cin>>test;
9 k=1;
10 while(test--)
11 {
12 cin>>n;
13 for(i=1;i<=n;i++)
14 cin>>a[i];
15 d[1]=a[1];
16 for(i=2;i<=n;i++)
17 {
18 if(d[i-1]<0) d[i]=a[i];
19 else d[i]=d[i-1]+a[i];
20 }
21 max=d[1];e=1;
22 for(i=2;i<=n;i++)
23 {
24 if(max<d[i])
25 {
26 max=d[i];e=i;
27 }
28 }
29 int t=0;
30 f=e;
31 for(i=e;i>0;i--)
32 {
33 t=t+a[i];
34 if(t==max) f=i;
35 }
36 cout<<"Case "<<k++<<":"<<endl<<max<<" "<<f<<" "<<e<<endl;
37 if(test) cout<<endl;
38 }
39 return 0;
40 }
 
改进后的只处理最大和不处理位置
View Code
 1 #include<cstdio>
 2 int main()
 3 {
 4     int n,test,ans,t,a,i;
 5     scanf("%d",&test);
 6     while(test--)
 7     {
 8         scanf("%d",&n);
 9         scanf("%d",&a);
10         ans=t=a;
11         for(i=1;i<n;i++) 
12         {
13             scanf("%d",&a);
14             if(t<0) t=a;
15             else t=t+a;
16             if(ans<t) ans=t;
17         }
18         printf("%d\n",ans);
19     }
20     return 0;
21 }

 

posted @ 2012-04-08 23:01  mtry  阅读(9855)  评论(0编辑  收藏  举报