题解:P13532 [OOI 2023] 购买礼物

· · 题解

LOJ 1st!

Solution

直接做不方便,如果能先确定 m_1 或 m_2 中的一个,再最小化 |m_1 - m_2| 就会方便很多。

我们先确定 m_1。为此,将 a 排序。设从大到小排序后的 a 的第 i 个位置在原数组对应的位置是 p_i。

这样,枚举 i 从 1 \sim n,则 m_1 = a_i 就确定下来了,而不受 j \in (i, n] 是选择 a_j 还是 b_{pos_j} 影响。现在的问题变成了,求 \min_{m_2} |m_1 - m_2|。

由于在 m_1 在 i 的位置取得了,因此所有的在 i 之前的位置 j 都必须选择 b_{pos_j}。 于是,m_2 至少要为 \max_{j = 1}^{i - 1} b_{pos_j},这个值在枚举 i 的时候直接维护即可。

那么在 i 后面的位置呢?由于 m_1 已经确定,因此对 j \in (i, n] 我们可以不受限制地进行最优化。由绝对值性质容易知道选择 \le m_1 的最大的数和 \ge m_1 的最小的数可以使 |m_1 - m_2| 取得尽可能小的值。这个可以使用 multiset 进行维护,在枚举 i 时不断删除其中的数即可。

时间复杂度 \Theta(n \log n),空间复杂度 \Theta(n)。

Code

#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iterator>
#include <set>
#define MAXN 500003
using namespace std;

namespace IO
{
#define SIZ (1 << 18)
    char ibuf[SIZ], *p1 = nullptr, *p2 = nullptr;
#define gc() (p1 == p2 && (p2 = (p1 = ibuf) + fread(ibuf, 1, SIZ, stdin), p1 == p2) ? EOF : *p1++)
    void rd(int &x)
    {
        x = 0;
        char c = gc();
        while (!isdigit(c))
            c = gc();
        while (isdigit(c))
            x = x * 10 + (c ^ 48), c = gc();
    }
#undef gc
#undef SIZ
}
using IO::rd;

struct Node
{
    int id, w;
    bool operator<(const Node &other) const
    {
        return w > other.w;
    }
} a[MAXN];
int b[MAXN];
multiset<int> st;

int main()
{
    int n, mx = 0, ans = 0x3f3f3f3f;
    rd(n);
    for (int i = 1; i <= n; ++i)
        a[i].id = i, rd(a[i].w), rd(b[i]), st.insert(b[i]);
    sort(a + 1, a + n + 1);
    multiset<int>::iterator it;
    for (int i = 1; i <= n; ++i)
    {
        st.erase(st.find(b[a[i].id]));
        ans = min(ans, abs(mx - a[i].w));
        it = st.lower_bound(a[i].w);
        if (it != st.end())
            ans = min(ans, abs(max(mx, *it) - a[i].w));
        if (it != st.begin())
            ans = min(ans, abs(max(mx, *prev(it)) - a[i].w));
        mx = max(mx, b[a[i].id]);
    }
    printf("%d", ans);
    return 0;
}