[NOI2016]区间
嘟嘟嘟
这题似乎不是很难。
自己口糊了一个\(O(n ^ 2)\)算法,搞了60分。思路就是先把区间离散化,然后枚举区间的公共点\(x_i\),再\(O(n)\)判断哪些区间包含这个点,然后观察到如果把这些区间按长度排序,可选的最优解一定是长度为\(m\)的连续一段区间,所以再\(O(n - m)\)扫一遍。
先把区间按长度排序,就是严格\(O(n ^ 2)\)了。
差点就能想到正解了。正解也是先把区间按长度排序,然后从头开始选区间,因为最优解一定是长度为\(m\)的连续一段,所以当有多于\(m\)个区间包含同一个点的时候,我们就扔掉长度最小的区间,直到恰有\(m\)个区间包含同一个点。
至于这个判断,用线段树就好了。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<ctime>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e6 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, lsh[maxn];
struct Node
{
int L, R, len;
In bool operator < (const Node& oth)const
{
return len < oth.len || (len == oth.len && L < oth.L);
}
}q[maxn];
int l[maxn << 2], r[maxn << 2], lzy[maxn << 2], Max[maxn << 2];
In void build(int L, int R, int now)
{
l[now] = L, r[now] = R;
if(L == R) return;
int mid = (L + R) >> 1;
build(L, mid, now << 1);
build(mid + 1, R, now << 1 | 1);
}
In void change(int now, int d)
{
Max[now] += d, lzy[now] += d;
}
In void pushdown(int now)
{
if(lzy[now])
{
change(now << 1, lzy[now]), change(now << 1 | 1, lzy[now]);
lzy[now] = 0;
}
}
In void update(int L, int R, int now, int d)
{
if(l[now] == L && r[now] == R) {change(now, d); return;}
pushdown(now);
int mid = (l[now] + r[now]) >> 1;
if(R <= mid) update(L, R, now << 1, d);
else if(L > mid) update(L, R, now << 1 | 1, d);
else update(L, mid, now << 1, d), update(mid + 1, R, now << 1 | 1, d);
Max[now] = max(Max[now << 1], Max[now << 1 | 1]);
}
int main()
{
n = read(), m = read();
for(int i = 1; i <= n; ++i)
{
int L = read(), R = read();
lsh[i] = L, lsh[n + i] = R;
q[i] = (Node){L, R, R - L};
}
sort(q + 1, q + n + 1);
sort(lsh + 1, lsh + n * 2 + 1);
int _n = unique(lsh + 1, lsh + n * 2 + 1) - lsh - 1;
build(1, _n, 1);
int ans = INF;
for(int j = 1, i = 1; i <= n; ++i)
{
q[i].L = lower_bound(lsh + 1, lsh + _n + 1, q[i].L) - lsh;
q[i].R = lower_bound(lsh + 1, lsh + _n + 1, q[i].R) - lsh;
update(q[i].L, q[i].R, 1, 1);
while(Max[1] >= m && j <= i)
{
update(q[j].L, q[j].R, 1, -1);
ans = min(ans, q[i].len - q[j++].len);
}
}
write(ans == INF ? -1 : ans), enter;
return 0;
}