hdu 5280 Senior's Array(dp)

来源:互联网 发布:linux中grep命令 编辑:程序博客网 时间:2024/04/28 18:36

Problem Description
One day, Xuejiejie gets an array A. Among all non-empty intervals of A, she wants to find the most beautiful one. She defines the beauty as the sum of the interval. The beauty of the interval---[L,R] is calculated by this formula : beauty(L,R) = A[L]+A[L+1]++A[R]. The most beautiful interval is the one with maximum beauty.

But as is known to all, Xuejiejie is used to pursuing perfection. She wants to get a more beautiful interval. So she asks Mini-Sun for help. Mini-Sun is a magician, but he is busy reviewing calculus. So he tells Xuejiejie that he can just help her change one value of the element of A to P . Xuejiejie plans to come to see him in tomorrow morning.

Unluckily, Xuejiejie oversleeps. Now up to you to help her make the decision which one should be changed(You must change one element).
 

Input
In the first line there is an integer T, indicates the number of test cases.

In each case, the first line contains two integers n and Pn means the number of elements of the array. P means the value Mini-Sun can change to. 

The next line contains the original array.

1n1000109A[i],P109
 

Output
For each test case, output one integer which means the most beautiful interval's beauty after your change.
 

Sample Input
23 51 -1 23 -21 -1 2
 

Sample Output
82



问题描述
某天学姐姐得到了一个数组A,在这个数组的所有非空区间中,她找出了一个区间和最大的,并把这个区间和定义为这个数组的美丽值。但是她觉得这个数组不够美,于是决定修理一下这个数组。学姐姐将会进行一次操作,把原数组中的某个数修改为P(必须修改)。最后她想使得修改后的数组尽可能美丽。请你帮助她计算经过修理后,这个数组的美丽值最大能是多少?
输入描述
第一行包含一个整数T,表示测试数据组数。对于每组测试数据:第一行包含两个整数nP,表示数组长度以及修改后的值。接下来一行包含n个整数A[i],表示初始的数组。1n1000, 109A[i],P109
输出描述
对于每组测试数据输出一个整数表示对应的答案。

官方题解报告:O(n)

从左往右处理出dp1[i]=max(a[i],dp1[i1]+a[i]),同样从右往左处理出dp2[i]=max(a[i],dp2[i+1]+a[i]),再枚举要修改哪一个数,用两个数组更新答案即可。

当然由于必须要修改一个A[i]为P,这个修改后的A[i]可能不包含在连续最大和中,也可能包含在连续最大和中,包含在其中的话就加上,不包含的话就舍掉。

#include <iostream>#include <string.h>using namespace std;int a[1002];long long dp1[1002],dp2[1002];int main(){    int t,n,p;    long long ans;    scanf("%d",&t);    while (t--)    {        memset(dp1, 0, sizeof(dp1));        memset(dp2, 0, sizeof(dp2));        ans=-1000000000000;        scanf("%d%d",&n,&p);        for (int i=1; i<=n; i++)            scanf("%d",&a[i]);        dp2[0]=dp2[n+1]=dp1[0]=dp1[n+1]=0;        for (int i=1; i<=n; i++)            dp1[i]=max(dp1[i-1]+a[i],(long long)a[i]);        for (int i=n; i>0; i--)            dp2[i]=max(dp2[i+1]+a[i],(long long)a[i]);        for (int i=1; i<=n; i++)        {            ans=max(ans,max(dp1[i-1], (long long)0)+max(dp2[i+1],(long long)0)+p); //包含在其中                        //不包含在其中,则就舍弃a[i],比较a[i]两边的序列,当然结果可能为负,所以不能包括dp1[0],dp2[n+1],因为这两者在前面初始化为0            if(i!=1)                ans=max(ans,dp1[i-1]);            if (i!=n)                ans=max(ans,dp2[i+1]);        }        printf("%lld\n",ans);            }    return 0;}

0 0
原创粉丝点击