Solution
直接做不方便,如果能先确定 或 中的一个,再最小化 就会方便很多。
我们先确定 。为此,将 排序。设从大到小排序后的 的第 个位置在原数组对应的位置是 。
这样,枚举 从 ,则 就确定下来了,而不受 是选择 还是 影响。现在的问题变成了,求 。
由于在 在 的位置取得了,因此所有的在 之前的位置 都必须选择 。 于是, 至少要为 ,这个值在枚举 的时候直接维护即可。
那么在 后面的位置呢?由于 已经确定,因此对 我们可以不受限制地进行最优化。由绝对值性质容易知道选择 的最大的数和 的最小的数可以使 取得尽可能小的值。这个可以使用 multiset 进行维护,在枚举 时不断删除其中的数即可。
时间复杂度 ,空间复杂度 。
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;
}