蓝桥杯 算法训练-礼物

时间:2025-03-26 17:31:23

问题描述

JiaoShou在爱琳大陆的旅行完毕,即将回家,为了纪念这次旅行,他决定带回一些礼物给好朋友。
在走出了怪物森林以后,JiaoShou看到了排成一排的N个石子。
这些石子很漂亮,JiaoShou决定以此为礼物。
但是这N个石子被施加了一种特殊的魔法。
如果要取走石子,必须按照以下的规则去取。
每次必须取连续的2*K个石子,并且满足前K个石子的重量和小于等于S,后K个石子的重量和小于等于S。
由于时间紧迫,Jiaoshou只能取一次。
现在JiaoShou找到了聪明的你,问他最多可以带走多少个石子。

输入格式

第一行两个整数N、S。
第二行N个整数,用空格隔开,表示每个石子的重量。

输出格式

第一行输出一个数表示JiaoShou最多能取走多少个石子。

样列输入

8 3
1 1 1 1 1 1 1 1

样列输出

6

解题思路

使用滑动窗口。

题目中连续两个字已经很明显的说明是一个滑动窗口的问题了。
算了,以后在补上题解吧,太晚了,直接复代码…
最后有两个需要注意的,因为每次j += 2,所以奇数和偶数都需要遍历一次。
另外如果后K个数字大于了S,能够通过移动mid解决,也就是移动 j j j解决。
所以分情况,正着来一遍,倒着来一遍,保证前面K个是以mid结尾的不超过s的最大长度。

//#define LOCAL
#include <bits/stdc++.h>
using namespace std ;


typedef long long LL;
const int N = 1e6 +10;

int a[N];
int n;
LL s;

int solve(int bg) {
    LL  pre = 0, suffix = 0;
    int i, j, ans = 0;
    for (i = bg, j = bg + 1; j < n; j += 2) {
        int mid = j + i >> 1;
        suffix += a[j - 1] + a[j] - a[mid];
        //printf("%d %d %d\n", i, j, mid);
        pre += a[mid];
        //printf("%lld %lld\n", pre, suffix);
        while(pre > s || suffix > s) {
            i += 2;
            mid = i + j >> 1;
            pre = pre - a[i - 1] - a[i - 2] + a[mid];
            suffix -= a[mid];
        }
        if(suffix <= s) ans = max(ans, j - i + 1);
    }
    return ans;
}

int main() {
# ifdef LOCAL
    freopen("", "r", stdin);

# endif // LOCLA

    cin >> n >> s;

    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    int ans = 0;
    //printf("%d\n", solve(0));
    ans = max(solve(0), solve(1));
    reverse(a, a + n);
    ans = max(max(ans, solve(0)), solve(1));
    printf("%d\n", ans);
    return 0;
}