永夜初晗凝碧天

本博客现已全部转移到新地址,欲获取更多精彩文章,请访问http://acshiryu.github.io/

导航

poj2479与poj2593 , 同一道DP题

Description

Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N). 

You should output S. 
这两道题的题目的题目大意如上,对于输入的n个数,求出最大的S
这是一个简单的DP题,开两个数组,DP[i][0],DP[i][1];
其中DP[i][0]表示的是从0~i中连续子串的最大和
DP[i][1]表示i~n-1中连续子串的最大和
则题目就变成求max{DP[i][0]+DP[i+1][1]}

http://www.cnblogs.com/ACShiryu

参考代码:

poj2479

 1 #include<iostream>
2 #include<cstdlib>
3 #include<cstdio>
4 #include<cstring>
5 #include<algorithm>
6 #include<cmath>
7 using namespace std;
8 int a[50005];
9 int dp[50005][2];
10 int i ;
11 int main()
12 {
13 int t ;
14 scanf("%d",&t);
15 while ( t -- )
16 {
17 int n ;
18 int sum=0;
19 scanf("%d",&n);
20 for ( i = 0 ; i < n ; i ++ )
21 {
22 scanf ("%d", &a[i]) ;
23 if ( i )
24 {
25 sum = max(sum+a[i],a[i]);
26 dp[i][0]=max(sum,dp[i-1][0]);
27 }
28 else
29 dp[i][0]=sum=a[i];
30 }
31 for ( i = n -1 ; i>=0 ; i -- )
32 {
33 if ( i != ( n - 1 ) )
34 {
35 sum = max(sum + a[i] , a[i]);
36 dp[i][1]=max(sum,dp[i+1][1]);
37 }
38 else
39 dp[i][1]=sum=a[i];
40 }
41 sum = -(1<<30) ;
42 for ( i = 0 ; i < n - 1 ; i ++ )
43 sum = max ( sum , dp[i][0]+dp[i+1][1] );
44 printf("%d\n",sum);
45 }
46 return 0;
47 }

  poj2593

 1 #include<iostream>
2 #include<cstdlib>
3 #include<cstdio>
4 #include<cstring>
5 #include<algorithm>
6 #include<cmath>
7 using namespace std;
8 int a[100005];
9 int dp[100005][2];
10 int i ;
11 int main()
12 {
13 int n ;
14 while ( scanf("%d",&n) , n )
15 {
16
17 int sum=0;
18 for ( i = 0 ; i < n ; i ++ )
19 {
20 scanf ("%d", &a[i]) ;
21 if ( i )
22 {
23 sum = max(sum+a[i],a[i]);
24 dp[i][0]=max(sum,dp[i-1][0]);
25 }
26 else
27 dp[i][0]=sum=a[i];
28 }
29 for ( i = n -1 ; i>=0 ; i -- )
30 {
31 if ( i != ( n - 1 ) )
32 {
33 sum = max(sum + a[i] , a[i]);
34 dp[i][1]=max(sum,dp[i+1][1]);
35 }
36 else
37 dp[i][1]=sum=a[i];
38 }
39 sum = -(1<<30) ;
40 for ( i = 0 ; i < n - 1 ; i ++ )
41 sum = max ( sum , dp[i][0]+dp[i+1][1] );
42 printf("%d\n",sum);
43 }
44 return 0;
45 }

posted on 2011-08-13 11:29  ACShiryu  阅读(508)  评论(0编辑  收藏  举报