Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:
- Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;
- Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units;
Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104).
The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).
In the single line print a single number — the answer to the problem.
3 4 4 19 1 42 3 99
576
4 7 2 3 9 1 2 3 4
34
Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.
The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.
题目大意:给你一个串,取的方法:左边取(*l)和右边取(*r),连续左(+ql),连续右(+qr);求取完和最小。
题目分析:乍一看是dp,但是仔细一想,这个题可以”乱搞“:首先我们想到当我们中间的界限确定以后(假设为点p),我们就得到了一个策略,在这个策略下,p点左边一定是左取的,即*l,p点包括p点右边一定右取,即*r,剩下的工作就是处理+ql,+qr,很容易想到,越少越好,就是间隔着左右左右取,当然,剩下的就要加起来(加的倍数为:左边个数与右边个数差的绝对值减一)。很容易想到暴力,就是遍历中间点p,我们看看复杂度,O(n2),显然要超。这个时候,就需要优化:我们可以预处理左右连续的和,假设为ll,rr数组,ll[i],rr[i]分别表示的当左边有i个连续的时候,左连续的和与右连续的和的值,这样复杂度就降了下来。大概是O(3*n)的复杂度。
总结:1、有的时候给你感觉很清楚是某个较难的知识点的时候,不要急着去写,稍微想一下,或许还有更简单的解。
2、简单地小优化有的时候是必要的,更是关键的。
AC代码:
#include<cstdio>
#include<cstring>
int w[100005];
int ll[100005],rr[100005];
int main()
{
int n,l,r,ql,qr;
while(scanf("%d %d %d %d %d",&n,&l,&r,&ql,&qr)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d",&w[i]);
int ans=99999999; ///太小会WA
memset(ll,0,sizeof ll);
memset(rr,0,sizeof rr);
for(int i=1;i<=n;i++) ///必要的预处理
ll[i]=ll[i-1]+w[i];
for(int i=n;i>=1;i--)
rr[i]=rr[i+1]+w[i];
for(int i=0;i<=n;i++)
{
int tmp=0;
tmp+=ll[i]*l;
tmp+=rr[i+1]*r;
if(i>n-i)
tmp+=(i-n+i-1)*ql;
else if(n-i>i)
tmp+=(n-i-1-i)*qr;
if(ans>tmp)
ans=tmp;
}
printf("%d\n",ans);
}
return 0;
}