4653: [Noi2016]区间
Time Limit: 60 Sec Memory Limit: 256 MBSubmit: 934 Solved: 500
[ 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
Sample Output
2
所有线段按长度从小到大排序,之后尺取
对于当前p和q,只考虑从第p条到第q条直线中取
将在[p, q]范围内的直线全部离加入线段树
如果线段树最值>=m,说明[p, q]范围内能取出刚好m条满足要求的直线,删除第p条直线,p++,
否则q++
ans = min(ans, len[q]-len[p])
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct Res
{
int len;
int l, r;
bool operator < (const Res &b) const
{
if(len<b.len)
return 1;
return 0;
}
}Line;
Line s[500005];
int cnt, k[1000015], tre[4004000], temp[4004000];
void Lazy(int l, int r, int x)
{
int m;
tre[x*2] += temp[x];
tre[x*2+1] += temp[x];
m = (l+r)/2;
if(l!=m)
temp[x*2] += temp[x];
if(m+1!=r)
temp[x*2+1] += temp[x];
temp[x] = 0;
}
void Update(int l, int r, int x, int a, int b, int c)
{
int m;
if(a==0 || b==0)
return;
if(l>=a && r<=b)
{
tre[x] += c;
if(l!=r)
temp[x] += c;
return;
}
if(temp[x])
Lazy(l, r, x);
m = (l+r)/2;
if(a<=m)
Update(l, m, x*2, a, b, c);
if(b>=m+1)
Update(m+1, r, x*2+1, a, b, c);
tre[x] = max(tre[x*2], tre[x*2+1]);
}
int main(void)
{
int n, m, i, p, q, ans;
scanf("%d%d", &n, &m);
for(i=1;i<=n;i++)
{
scanf("%d%d", &s[i].l, &s[i].r);
k[++cnt] = s[i].l, k[++cnt] = s[i].r;
s[i].len = s[i].r-s[i].l;
}
sort(s+1, s+n+1);
sort(k+1, k+cnt+1);
cnt = unique(k+1, k+cnt+1)-(k+1);
for(i=1;i<=n;i++)
{
s[i].l = lower_bound(k+1, k+cnt+1, s[i].l)-k;
s[i].r = lower_bound(k+1, k+cnt+1, s[i].r)-k;
}
p = 1, q = 0;
ans = 2147483647;
while(q<=n && p<=n)
{
while(tre[1]<m && q<=n)
{
q++;
Update(1, cnt, 1, s[q].l, s[q].r, 1);
}
while(tre[1]>=m)
{
ans = min(ans, s[q].len-s[p].len);
Update(1, cnt, 1, s[p].l, s[p].r, -1);
p++;
}
}
if(ans==2147483647)
printf("-1\n");
else
printf("%d\n", ans);
return 0;
}