POJ 2479 Maximum sum && POJ 2593 Max Sequence

来源:互联网 发布:蚁群算法 python 编辑:程序博客网 时间:2024/06/06 02:44

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

1101 -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.

Source

POJ Contest,Author:Mathematica@ZSU

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DP~

神奇的动态规划……每次遇到这题都会错……注意区间是连续的啊!

然后,分别用f1,f2表示从左往右和从右往左的包含i的最长子序列的值,然后用f3表示i右面的最长子序列的值,最后用f1[i-1]+f3[i]更新ans即可~

注意f1下标是i-1,因为两个区间不相连~样例真是良心~

(两道题一模一样就一起发了~)


2479的程序:

#include<cstdio>#include<iostream>using namespace std;int t,n,a[100001],f1[100001],f2[100002],f3[100002],ans;int main(){scanf("%d",&t);while(t--){scanf("%d",&n);f1[0]=f2[n+1]=f3[n+1]=ans=-10001;for(int i=1;i<=n;i++) scanf("%d",&a[i]);for(int i=1;i<=n;i++) f1[i]=max(a[i],f1[i-1]+a[i]);for(int i=n;i;i--){f2[i]=max(a[i],f2[i+1]+a[i]);f3[i]=max(f3[i+1],f2[i]);ans=max(ans,f3[i]+f1[i-1]);}printf("%d\n",ans);}return 0;}



2593的程序~

#include<cstdio>#include<iostream>using namespace std;int n,a[100001],f1[100001],f2[100002],f3[100002],ans;int main(){while(scanf("%d",&n)==1 && n){f1[0]=f2[n+1]=f3[n+1]=ans=-10001;for(int i=1;i<=n;i++) scanf("%d",&a[i]);for(int i=1;i<=n;i++) f1[i]=max(a[i],f1[i-1]+a[i]);for(int i=n;i;i--){f2[i]=max(a[i],f2[i+1]+a[i]);f3[i]=max(f3[i+1],f2[i]);ans=max(ans,f3[i]+f1[i-1]);}printf("%d\n",ans);}return 0;}


1 0