1. 程式人生 > >Maximum sum-動態規劃

Maximum sum-動態規劃

ddl border 數組 clear fonts nts input gree img

技術分享

A - Maximum sum Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit Status Practice POJ 2479

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
技術分享
Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Sample Input

1

10
1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended.
/*
Author: 2486
Memory: 544 KB		Time: 438 MS
Language: C++		Result: Accepted
*/
//題目思路是從左到右分別求出它們所在位置的最大連續和,然後從右到左求出它們所在的最大連續和
//接著就是a[i]+b[i+1],a數組代表著從左到右,b代表著從右到左所以不斷的比較a[0]+b[1],a[1]+b[2]求最大值就可以
//如何求解最大值(代碼最後段有具體解釋)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=50000+5;
int n,m;
int a[maxn];
int dp[maxn];
int main() {
    scanf("%d",&n);
    while(n--) {
        scanf("%d",&m);
        for(int i=0; i<m; i++) {
            scanf("%d",&a[i]);
        }
        dp[0]=a[0];
        int sum=a[0];
        int ans=a[0];
        for(int i=1; i<m; i++) {
            if(sum<0) {
                sum=0;
            }
            sum+=a[i];
            if(sum>ans) {
                ans=sum;
            }
            dp[i]=ans;
        }
        sum=a[m-1];
        int Max=dp[m-2]+sum;
        ans=a[m-1];
        for(int j=m-2; j>=1; j--) {
            if(sum<0) {
                sum=0;
            }
            sum+=a[j];
            if(sum>ans) {
                ans=sum;
            }
            Max=max(Max,dp[j-1]+ans);
        }
        printf("%d\n",Max);
    }


    return 0;

}

假設當前的數據和小於零。非常明顯,將它增加到後面的計算中,肯定會降低最大值
非常easy的道理。-1+4<0+4,假設之前的取值小於零,拋棄它,又一次賦值為零
然後通過maxs不斷更新當前的最大值
while(true){
scanf("%d",&a);
if(sum<0) {
sum=0;
}
sum+=a;
if(sum>maxs) {
maxs=sum;
}
}

Maximum sum-動態規劃