const int N=5e5+5;
int n,m;
int i,j,k;
int a[N];
struct Node
{
int l,r;
int ll,rr;
bool operator<(Node o){
//if(o.r==r) return l<o.l
//return r<o.r;
return r-l<o.r-o.l;
}
void read(){ sdd(l,r); }
}seg[N];
struct Tree
{
int l,r;
int maxx,lazy;
void update(int x)
{
lazy+=x;
maxx+=x;
}
#define lson id<<1
#define rson id<<1|1
}t[N<<3];
vector<int> v;
int getid(int x)
{
return lower_bound(v.begin(),v.end(),x)-v.begin()+1;
}
void push_up(int id)
{
t[id].maxx=max(t[lson].maxx,t[rson].maxx);
}
void push_down(int id)
{
int x=t[id].lazy;
if(x){
t[lson].update(x);
t[rson].update(x);
t[id].lazy=0;
}
}
void build(int l,int r,int id)
{
t[id].l=l,t[id].r=r;
t[id].maxx=0;
if(l==r) return ;
else{
int mid=l+r>>1;
build(l,mid,lson);
build(mid+1,r,rson);
push_up(id);
}
}
void update(int l,int r,int c,int id)
{
int L=t[id].l,R=t[id].r;
if(L>=l && r>=R) t[id].update(c);
else{
int mid=L+R>>1;
push_down(id);
if(mid>=l) update(l,r,c,lson);
if(r>=mid+1) update(l,r,c,rson);
push_up(id);
}
}
int main()
{
//IOS;
while(~sdd(n,m)){
forn(i,1,n) seg[i].read(),v.pb(seg[i].l),v.pb(seg[i].r);
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
forn(i,1,n) seg[i].ll=getid(seg[i].l),seg[i].rr=getid(seg[i].r);
sort(seg+1,seg+1+n);
build(1,1e6,1);
int ans=inf;
int cur=1;
for(int i=1;i<=n;i++){
update(seg[i].ll,seg[i].rr,1,1);
while(t[1].maxx==m){
int res=(seg[i].r-seg[i].l)-(seg[cur].r-seg[cur].l);
ans=min(ans,res);
update(seg[cur].ll,seg[cur].rr,-1,1);
cur++;
}
}
if(ans==inf) ans=-1;
pd(ans);
}
//PAUSE;
}
Shenzhou III number serial port 2 Send experimental program
2023-01-23
ES