(分析见正睿2018.10.1笔记)
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<ctime>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
const int inf = 2e9+7;
int d[4001000],col[4001000],n,m,b[1000100],b2[500100],sum,sum2,cnt,S;
int back2[500100];
map<int,int>id,id2;
struct node{
int x,y,len;
};
node a[500100];
inline int ra(){
int x=0;char s=getchar();
while(!isdigit(s))s=getchar();
while(isdigit(s))x=(x<<3)+(x<<1)+(s-'0'),s=getchar();
return x;
}
inline bool cmp(const node p,const node q){
return p.len<q.len;
}
inline void update(int le,int ri,int wh,int x,int y,int k){
if(le>=x&&ri<=y){
d[wh]+=k;
col[wh]+=k;
return;
}
int mid=(le+ri)>>1;
col[wh<<1]+=col[wh];
col[wh<<1|1]+=col[wh];
d[wh<<1]+=col[wh];
d[wh<<1|1]+=col[wh];
col[wh]=0;
if(mid>=x)update(le,mid,wh<<1,x,y,k);
if(mid<y)update(mid+1,ri,wh<<1|1,x,y,k);
d[wh]=max(d[wh<<1],d[wh<<1|1]);
return;
}
int main(){
register int i,j,k,t;
int Ans=inf;
n=ra(),m=ra();
for(i=1;i<=n;++i){
a[i].x=ra(),a[i].y=ra();
if(a[i].x>a[i].y)swap(a[i].x,a[i].y);
a[i].len=a[i].y-a[i].x;
b[++cnt]=a[i].x;
b[++cnt]=a[i].y;
b2[++S]=a[i].y-a[i].x;
}
sort(b+1,b+cnt+1);
sort(b2+1,b2+S+1);
for(i=1;i<=cnt;++i)
if(!id[b[i]])id[b[i]]=++sum;
for(i=1;i<=S;++i)
if(!id2[b2[i]])id2[b2[i]]=++sum2,back2[sum2]=b2[i];
for(i=1;i<=n;i++){
a[i].len=id2[a[i].len];
a[i].x=id[a[i].x];
a[i].y=id[a[i].y];
}
sort(a+1,a+n+1,cmp);
j=0;k=1;t=1;
for(k;k<=n;++k)
if(a[k].len<=1){
update(1,sum,1,a[k].x,a[k].y,1);
}else break;
for(i=1;i<=sum2;++i){
while(j<sum2&&d[1]<m){
j++;
for(k;k<=n;++k)
if(a[k].len<=j){
update(1,sum,1,a[k].x,a[k].y,1);
}else break;
}
if(d[1]>=m)Ans=min(Ans,back2[j]-back2[i]);
else break;
if(i!=n)
for(t;t<=n;++t)
if(a[t].len<=i){
update(1,sum,1,a[t].x,a[t].y,-1);
}else break;
}
if(Ans==inf)Ans=-1;
printf("%d
",Ans);
return 0;
}