Computer Science Gym - 101510C
Computer Science Gym-101510C
Description:
Vera has N integers a1, …, aN. A margin is a non-negative integer L such that it is possible to choose N integers x1, …, xN such that for all i, 1 ≤ i ≤ N, the interval [xi, xi + L] contains at least K of Vera’s integers and also contains ai.
Compute the minimum possible margin.
Input
Line 1 contains integers N and K (1 ≤ K ≤ N ≤ 2 × 105).
Line 2 contains N integers, a1, …, aN ( - 109 ≤ ai ≤ 109).
Output
Print one line with one integer, the minimum possible margin.
Example
Input
5 3
1 -2 10 5 4
Output
6
题目大意:
给出数列 ai 和 N,K
要求构造出一个 序列 xi,每个 xi 满足 在 [xi,xi+L]中存在有 K 个 ai 中的数.并且包含 ai
求出最小的 L
分析:
对于要求 xi 包含 ai ,因为对 xi 的顺序没有要求,所以题目等价于维护一个长度为 L 的区间,使得每个区间内存在 K 个数字(ai), 并且每个数字都被一个区间覆盖.
对 ai 排序,二分L,对于每个 L,check函数用一个区间去扫整个 ai
扫描时用左右两个游标控制,
处理过程中需要保证每个ai都被包含
即条件 l<= i <=r
代码:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#pragma warning(disable:4996)
#pragma comment(linker, "/STACK:336777216")
using namespace std;
int a[200010],n,k;
int check(int x)
{
int i,b,l,r;
b=1;
l=1; r=k;
for (i=1;i<=n;i++)
{
while (a[r]-a[l]>x&&l<i&&r<n||r<i) {l++; r++;}
if (a[r]-a[l]>x)
{
b=0;
break;
}
}
return b;
}
int main()
{
int l,f,i;
long long le,ri,mid;
cin>>n>>k;
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
le=1; ri=a[n]-a[1];
while (le<ri)
{
mid=(le+ri)/2;
if (!check(mid)) le=mid+1;
else ri=mid;
}
cout<<ri<<endl;
return 0;
}