16 年的 NOI,现在只有 tg T2 的水准了……
考虑对区间长度排序,然后用一个双指针维护现在选哪一段区间的区间,只要满足被覆盖的最多的点覆盖了 $t$ 次就更新答案,并不断把前面的区间删掉。
要离散化。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 15;
struct node {
int l, r, len;
} a[N];
int b[N], n, m, t;
bool cmp(node a, node b) { return a.len < b.len; }
struct Tree {
int l, r;
int Max, flag;
} tr[N << 2];
void pushup(int u) {
tr[u].Max = max(tr[u << 1].Max, tr[u << 1 | 1].Max);
}
void pushdown(int u) {
if (tr[u].flag) {
tr[u << 1].flag += tr[u].flag;
tr[u << 1 | 1].flag += tr[u].flag;
tr[u << 1].Max += tr[u].flag;
tr[u << 1 | 1].Max += tr[u].flag;
tr[u].flag = 0;
}
}
void build(int u, int l, int r) {
tr[u].l = l, tr[u].r = r;
tr[u].Max = tr[u].flag = 0;
if (l == r) return;
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
void change(int u, int l, int r, int d) {
if (l > r || tr[u].r < l || tr[u].l > r) return;
if (tr[u].l >= l && tr[u].r <= r) {
tr[u].Max += d, tr[u].flag += d;
return;
}
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) change(u << 1, l, r, d);
if (r > mid) change(u << 1 | 1, l, r, d);
pushup(u);
}
int main() {
scanf("%d%d", &n, &t);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].l, &a[i].r);
a[i].len = a[i].r - a[i].l + 1;
b[++m] = a[i].l, b[++m] = a[i].r;
}
sort(b + 1, b + 1 + m);
m = unique(b + 1, b + 1 + m) - b - 1;
for (int i = 1; i <= n; i++) {
a[i].l = lower_bound(b + 1, b + 1 + m, a[i].l) - b;
a[i].r = lower_bound(b + 1, b + 1 + m, a[i].r) - b;
}
sort(a + 1, a + 1 + n, cmp);
// for (int i = 1; i <= n; i++) cout << a[i].l << ' ' << a[i].r << ' ' << a[i].len << endl;
build(1, 1, m);
int ans = 0x3f3f3f3f;
for (int i = 1, j = 1; i <= n; i++) {
change(1, a[i].l, a[i].r, 1);
while (tr[1].Max > t) change(1, a[j].l, a[j].r, -1), j++;
while (tr[1].Max == t) ans = min(ans, a[i].len - a[j].len), change(1, a[j].l, a[j].r, -1), j++;
}
if (ans == 0x3f3f3f3f) puts("-1");
else printf("%d\n", ans);
return 0;
}