[Noi2016]区间
传送门
Code
/*
线段树 尺取法
*/
#include<bits/stdc++.h>
#define ll long long
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)>(b)?(b):(a))
#define reg register
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return x*f;
}
const int MN=1e6+5;
struct x{
int l,r,len;
bool operator<(const x&o)const{return len<o.len;}
}a[MN];
int N,M,num[MN<<1];
int T[MN<<2],lazy[MN<<2];
void down(int k)
{
if(lazy[k])
{
int y=lazy[k];
lazy[k<<1]+=y;lazy[k<<1|1]+=y;
T[k<<1]+=y;T[k<<1|1]+=y;
lazy[k]=0;
}
}
void Modify(int k,int l,int r,int a,int b,int v)
{
if(l==a&&r==b)
{
T[k]+=v;lazy[k]+=v;
return;
}
down(k);int mid=(l+r)>>1;
if(b<=mid) Modify(k<<1,l,mid,a,b,v);
else if(a>mid) Modify(k<<1|1,mid+1,r,a,b,v);
else Modify(k<<1,l,mid,a,mid,v),Modify(k<<1|1,mid+1,r,mid+1,b,v);
T[k]=max(T[k<<1],T[k<<1|1]);
}
int main()
{
reg int i,j;
N=read(),M=read();
for(i=1;i<=N;++i)a[i].l=read()+1,a[i].r=read()+1,a[i].len=a[i].r-a[i].l;
std::sort(a+1,a+N+1);
for(i=1;i<=N;++i) num[i*2-1]=a[i].l,num[i<<1]=a[i].r;
std::sort(num+1,num+N*2+1);
int n=std::unique(num+1,num+N*2+1)-num-1;
int ans=1e9+6;
for(j=1,i=1;i<=N;++i)
{
int L=std::lower_bound(num+1,num+n+1,a[i].l)-num;
int R=std::lower_bound(num+1,num+n+1,a[i].r)-num;
a[i].l=L,a[i].r=R;
Modify(1,1,n,L,R,1);
for(;T[1]>=M&&i>=j;++j)
ans=min(ans,a[i].len-a[j].len),
Modify(1,1,n,a[j].l,a[j].r,-1);
}
if(ans>1e9) ans=-1;
return 0*printf("%d\n",ans);
}
Blog来自PaperCloud,未经允许,请勿转载,TKS!
致虚极,守静笃,万物并作,吾以观其复