LA3177贪心+二分

题目链接点击这里

思路

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

  • 当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;
}

猜你喜欢

转载自blog.csdn.net/crazy_scott/article/details/80203492