[デイリー質問]:最大化ビューティフル値

トピック:

例:

効果の件名:

给出一个单调不递减序列(只是说单调不递减哦),然后给一个 K ,可以使得数列中的一个数向前移动 K 步,
其他的依次向后移动,最后使得 1 * a[1] + 2 * a[2] + 3 * a[3] + ..... + a[n] 最大(移动后)。

Xitidekan:

刚开始看样例一位只要 将最后一位向前移动 K 步就 ok 了,交了一发,哈哈,wa 的可伶,
其实这样是肯定不行的,试想这样一个样例: 1 1 1 1 2 2 
K = 3,这样的话是满足单调不递减的,但是如果我们将最后一位向前移动 K 步的话,显然我们得到的值不是最大的。
我们只需要将前面的 1 向前移动 K 步即可。

検査ポイント:

贪心、前缀和、思维

グラフィック:

コード:

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 1e5 + 10;

typedef long long LL;

LL a[maxn];

LL pre[maxn];

LL res = 0,ans = 0;

int t,n,k;

int main(void) {
    scanf("%d",&t);
    while(t --) {
        res = 0,ans = 0;
        scanf("%d%d",&n,&k);
        for(int i = 1; i <= n; i ++) {
            scanf("%d",&a[i]);
            // 总和
            ans += a[i] * i;
            // 前缀和
            pre[i] = pre[i - 1] + a[i];
        }
        res = 0;
        for(int i = k + 1; i <= n; i ++) {
            // 每个 A【i】只能向前移动 K 步
            res = max(res,ans + (pre[i - 1] - pre[i - k - 1]) - a[i] * k);
        }
        printf("%lld\n",res);
    }
    return 0;
    
}

背後Keguanステー:

思维真的是个奇妙的东西。
先看一下限制范围,猜一下大概会用到什么算法,通过题目去推测信息显得尤为重要,
我们在做一个选择的时候应该想想会造成什么影响。

おすすめ

転載: www.cnblogs.com/prjruckyone/p/12670264.html