Description
Solution
注意到答案区间两端一定都在给定的2*n个端点上,所以我们可以根据单调性移动双指针即可
Code
const int inf=1e9+10;
struct node{
int id, op;
//0 st 1 ed
}a[maxn];
bool cmp(node x, node y) {return x.id < y.id;}
int main(int argc, char const *argv[])
{
int t,n,p;
scanf ("%d",&t);int cas = 0;
while (t--){
scanf ("%d%d",&n,&p);
for(int i = 1;i <= n;++i) {
int st,ed;scanf("%d %d",&st,&ed);
a[i] = {st,0}, a[i+n] = {ed,1};
}sort(a + 1,a + 1 + 2 * n,cmp);
int i = 0, j = 1, k = 0;
int ans=inf;
while (j<=2*n){
if (a[j].op==0) k++;
while (k>=p && i<j) {
ans=min(ans,a[j].id-a[i+1].id);
i++;
if (a[i].op==1) k--;
}
j++;
}
printf ("Case %d: %d\n",++cas,ans);
}
return 0;
}