LA3177贪心+二分

博客介绍了如何运用贪心策略和二分搜索解决一道题目。对于偶数个礼物,最优解是选取两个相邻的礼物;奇数个礼物时,通过分治策略和二分查找优化,递归检查不同分配方案的可行性,以确保最后一人能获得最多的礼物。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接点击这里

思路

此题分奇偶两种情况进行讨论:

  • 当n为偶数时,很容易证明最优解就是两个相邻的数的和最大;
  • 当n为奇数时,不太好处理

我们想,当n为奇数时,若假设这时候p个礼物满足条件,第一个人将p个礼物分为1,…,r1和r1,…,p这两种情况,第i个人若为奇数,则要尽量往r1,…,p取,同样,若第i个人为偶数,则要尽量往1,…r1取,这样可以使得最后一个人(奇数)能取到尽可能多的数。

实现

  • 由于此题只需要输出最优解,因此我们维护两个数组RightLeft,分别表示第i个人在两个范围内的取值情况,依次递归即可检验p个礼物是否可行。
  • 很容易验证p的最大值为礼物最大数的3倍,因此可以使用二分法减少迭代次数。
#include <iostream>

using namespace std;

int n;

const int maxn = 1000000 + 10;
int guard[maxn], Left[maxn], Right[maxn];

int test(int p)
/* Left = [1,...,r1]
   Right = [r1+1,...p]
 */
{
    int x = guard[1], y = p - guard[1];
    Left[1] = x;
    Right[1] = 0;
    for (int i = 2 ;i <= n; i++)
    {
        if (i % 2)
        /* if odd */
        {
            /* get Right side as much as posible, except those token by i-1 */
            Right[i] = min(y - Right[i - 1], guard[i]);
            Left[i] = guard[i] - Right[i];
        }
        else
        /* if even */
        {
            /* get Left side as much as posible, except those token by i -1 */
            Left[i] = min(x - Left[i - 1], guard[i]);
            Right[i] = guard[i] - Left[i];
        }
    }
    /* test Left side of n is zero,if zero, p is ok */
    return Left[n] == 0;
}

int main()
{
    while (cin >> n && n)
    {
        for (int i = 1; i <= n; i++)
        {
            cin >> guard[i];
        }
        guard[n + 1] = guard[1];

        if (n == 1)
        {
            cout << guard[1] << endl;
            continue;
        }
        int R = 0, L = 0;
        for (int i = 1; i <= n; i++)
            L = max(L, guard[i + 1]+guard[i]);
        if (n % 2)
        {
            for (int i = 1; i <= n; i++)
                R = max(R, guard[i] * 3);
            while (L < R)
            {
                int middle = (R + L) / 2;
                if (test(middle))
                    R = middle;
                else
                    L = middle + 1;
            }
        }
        cout << L << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值