4653: [Noi2016]区间
Time Limit: 60 Sec Memory Limit: 256 MBSubmit: 168 Solved: 103
[ Submit][ Status][ Discuss]
Description
在数轴上有 n个闭区间 [l1,r1],[l2,r2],...,[ln,rn]。现在要从中选出 m 个区间,使得这 m个区间共同包含至少一个位置。换句话说,就是使得存在一个 x,使得对于每一个被选中的区间 [li,ri],都有 li≤x≤ri。
对于一个合法的选取方案,它的花费为被选中的最长区间长度减去被选中的最短区间长度。区间 [li,ri] 的长度定义为 ri−li,即等于它的右端点的值减去左端点的值。
求所有合法方案中最小的花费。如果不存在合法的方案,输出 −1。
Input
第一行包含两个正整数 n,m用空格隔开,意义如上文所述。保证 1≤m≤n
接下来 n行,每行表示一个区间,包含用空格隔开的两个整数 li 和 ri 为该区间的左右端点。
N<=500000,M<=200000,0≤li≤ri≤10^9
Output
只有一行,包含一个正整数,即最小花费。
Sample Input
6 3
3 5
1 2
3 4
2 2
1 5
1 4
3 5
1 2
3 4
2 2
1 5
1 4
Sample Output
2
HINT
Source
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<bitset>
#include<algorithm>
#include<cstring>
#include<map>
#include<stack>
#include<set>
#include<cmath>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;
const int maxn = 5E5 + 50;
const int INF = ~0U>>1;
struct data{
int l,r,len;
data (int _l = 0,int _r = 0) {l = _l; r = _r; len = r - l;}
bool operator < (const data &b) const {return len < b.len;}
}Q[maxn];
int n,m,ans = INF,cnt,cur = 1,a[maxn*2],b[maxn*4],Max[maxn*30],Mark[maxn*30];
void pushdown(int o)
{
if (Mark[o]) {
Max[2*o] += Mark[o]; Mark[2*o] += Mark[o];
Max[2*o+1] += Mark[o]; Mark[2*o+1] += Mark[o];
Mark[o] = 0;
}
}
void Modify(int o,int l,int r,int ml,int mr,int Add)
{
pushdown(o);
if (ml <= l && r <= mr) {Max[o] += Add; Mark[o] += Add; return;}
int mid = (l + r) >> 1;
if (ml <= mid) Modify(2*o,l,mid,ml,mr,Add);
if (mr > mid) Modify(2*o+1,mid+1,r,ml,mr,Add);
Max[o] = max(Max[2*o],Max[2*o+1]);
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
cin >> n >> m; int tot = 0;
for (int i = 1; i <= n; i++) {
int l,r; scanf("%d%d",&l,&r);
Q[i] = data(l,r);
a[++tot] = l; a[++tot] = r;
}
sort(Q + 1,Q + n + 1);
sort(a + 1,a + tot + 1);
for (int i = 2; i <= tot; i++)
if (a[i] != a[i-1])
a[++cur] = a[i];
b[tot = 1] = a[1];
for (int i = 2; i <= cur; i++) {
if (a[i] - a[i-1] > 1) b[++tot] = a[i-1] + 1;
b[++tot] = a[i];
}
int L = 1;
for (int R = 1; R <= n; R++) {
Q[R].l = lower_bound(b + 1,b + tot + 1,Q[R].l) - b;
Q[R].r = lower_bound(b + 1,b + tot + 1,Q[R].r) - b;
Modify(1,1,tot,Q[R].l,Q[R].r,1);
for (;;) {
if (Max[1] < m || L == R) break;
ans = min(ans,Q[R].len - Q[L].len);
Modify(1,1,tot,Q[L].l,Q[L].r,-1);
++L;
}
}
if (ans == INF) cout << -1; else cout << ans;
return 0;
}