题解:P9982 [USACO23DEC] Haybale Distribution G

· · 题解

其实这道题没那么难,像我这样的蒟蒻都可以自主 AC。

我们知道,一个选点由左右两边的谷仓提供贡献,左边的贡献就是左边所有的谷仓移动到它的距离之和乘上 a,同理,右边的贡献就是右边所有的谷仓移动到它的距离之和乘上 b。这里要注意读题,我们是在一个点放了一堆干草堆,然后运到谷仓,所有左边的谷仓乘上的是 a,因为是右边的干草堆运到左边的谷仓;在右边的谷仓同理。

我们先想到对于每次的选点,枚举每个谷仓,算出它提供的贡献,但是这样每次枚举是 O(n) 的,看到范围就知道肯定会超时,所以我们想想如何优化。

我们发现,对于每个选点,它两边所有谷仓到它的距离是固定的,只是 a,b 有变化,所以我们可以先预处理出每个选点左右两边谷仓到它的距离,这样可以做到 O(1) 复杂度。

然后我们从左到右枚举当前选点一遍再从右往左枚举一遍,分别算出左右两边到每个选点的距离。但由于谷仓下标不是有序的,所以我们手动排序两边,pre,nxe 记录的是已经有多少个谷仓在当前选点的左或右边,这样我们可以确定每个选点两边谷仓到它的距离。枚举下一个谷仓的数组下标要加一,另外要特判防止是否所有的谷仓都在当前选点的一边。

有一个注意点:因为选点坐标为 0 时访问 p[-1] 会越界,所以我们没有在第一次循环里加上 0,但是有的谷仓的位置在 0,所以我们先把位置为 0 的谷仓个数计算了。

由于我们无法保证答案是有序的,所以使用三分,而整数的三分最后弹出循环操作是范围内点个数小于等于 3,然后还要再枚举这几个数,取最小值,记得开 long long。

最后给出代码(这道题挺简单的,不知道为什么一些题解做法那么复杂,还是说我的做法要被 hack?):

//Just Sayori
#pragma GCC diagnostic ignored "-Wnarrowing"
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#define ll long long
#define rnt register int
#define gr getchar
#define pr putchar
#define N 500005
#define M 1000000007
using namespace std;
inline ll read()
{
    ll x = 0, f = 1;
    char ch = gr();
    while (ch < '0' || ch > '9') ch == '-' ? f = -1, ch = gr() : ch = gr();
    while (ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + (ch ^ 48), ch = gr();
    return x * f;
}
inline void write(ll x)
{
    static int top = 0, sta[39];
    if (x < 0) pr('-'), x = -x;
    do sta[++top] = x % 10, x /= 10;
    while (x);
    while (top) pr(sta[top--] ^ 48);
}
#define eps 1e-9
ll n, m, a, b, pre, nxe;
ll p[N << 1], q[N << 1], x[N];
ll f(int x)
{
    return (a * 1ll * p[x] + b * 1ll * q[x]);
}
int main()
{
    n = read();
    for (rnt i = 1; i <= n; i++) x[i] = read();
    sort(x + 1, x + n + 1);//排序
    p[0] = 0;
    while (x[pre + 1] <= 0 && pre < n) pre++;//找到位置为 0 的谷仓
    for (rnt i = 1; i <= 1000000; i++)
    {
        p[i] = p[i - 1] + pre;
        while (x[pre + 1] <= i && pre < n)//注意加一
            pre++;
    }
    sort(x + 1, x + n + 1, greater<int>());
    for (rnt i = 1000000; i >= 0; i--)
    {
        q[i] = q[i + 1] + nxe;
        while (x[nxe + 1] >= i && nxe < n)
            nxe++;
    }
    m = read();
    while (m--)
    {
        a = read(), b = read();
        int l = 0, r = 1000000;
        while (r - l > 3)//三分
        {
            int mid1 = l + (r - l) / 3, mid2 = r - (r - l) / 3;
            if (f(mid1) > f(mid2))
                l = mid1;
            else
                r = mid2;
        }
        ll ans = 0x3f3f3f3f3f3f3f3f;//取最小值
        for (rnt i = l; i <= r; i++)
            ans = min(ans, f(i));
        write(ans), pr(10);
    }
    return 0;
}

感谢您的观看!