Maximize The Beautiful Value
发布时间: 2017年5月14日 19:26 最后更新: 2017年5月14日 19:30 时间限制: 2000ms 内存限制: 128M
Today HH finds a non-decreasing sequence (a1,a2....an,ai≤ai+1) , he thinks it's not beautiful so he wants to make it beautiful.
To make it, HH will choose exactly one number and move it forward at least k steps(i.e. you can move ai to aj if k≤i−j ), and then he defines the beautiful value F(n) as ∑ni=1i×ai .
HH asks you to calculate max(F(n))
The first line contains an positive integer
T(1≤T≤10)
, represents there are
T
test cases.
For each test case:
The first line contains two positive integers
n,k(1≤n≤105,1≤k<n)
,the length of the sequence ,the least steps you need to move.
The second line contains
n
integers
a1,a2…an
(
1≤ai≤108
) - the sequence.
For each test case, you should output the max F(n) .
3 5 3 1 1 3 4 5 5 2 1 1 3 4 5 5 1 1 1 3 4 5
46 50 53
In the first example, you can move the fifth number 4 for 3 steps and make the sequence become [ 4,1,1,3,5 ], then the beautiful value is 4×1+1×2+1×3+3×4+5×5=46 .
You can also move the fifth number to make it become [ 1,5,1,3,4 ], the beautiful value is also 46.
In the second example, you can move the fifth number 5 for 2 steps and make the sequence become [ 1,1,5,3,4 ]
In the second example, you can move the second number
1
for
1
steps and then the sequence is still [
1,1,3,4,5
]
scanf is commended。
题意:输入n,k,总共n个数,并且这n个数是非减的;选择一个数字最少要向前移动k个数,然后求出移动后的值;问移动哪一个数能够使得值为最大;求值:i*a[i] (i:1~n);
思路:因为这n个数是非减的,列出几个样例就可以知道只向前移动k步是最优的,不能再向前多移动,否则值会减小;开辟三个数组:a[]:本来的数,b[]:对a[]的前缀和;c[i]:i*a[i];S[i]:对c[]的前缀和;注意:处理的前缀和b[0]=0,S[0]=0;将数列分为3部分,比如n== 9,k==2;我们将第6个数向前移动k位应该是这样:
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100005;
typedef long long ll;
ll a[maxn],b[maxn],c[maxn];
ll S[maxn];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(S,0,sizeof(S));
int n,k;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
b[i]=b[i-1]+a[i];
c[i]=i*a[i];
S[i]=S[i-1]+c[i];
}
// for(int i=1;i<=n;i++)
// printf("%lld ",b[i]);
// printf("\n");
// for(int i=1;i<=n;i++)
// printf("%lld ",c[i]);
// printf("\n");
// for(int i=1;i<=n;i++)
// printf("%lld ",S[i]);
// printf("\n");
ll ans=0,sum1=0,sum2=0,sum3=0,sum=0;
for(int i=k+1;i<=n;i++)
{
sum1=S[i-k-1];
sum2=S[i-1]-S[i-k-1]+b[i-1]-b[i-k-1]+c[i]-k*a[i];
sum3=S[n]-S[i];
//printf("%lld %lld %lld \n",sum1,sum2,sum3);
sum=sum1+sum2+sum3;
// printf("%lld\n",sum);
ans=max(sum,ans);
}
printf("%lld\n",ans);
}
return 0;
}