Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:
- Each pencil belongs to exactly one box;
- Each non-empty box has at least k pencils in it;
- If pencils i and j belong to the same box, then |ai - aj| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≤ d and they belong to different boxes.
Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
The first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·105, 0 ≤ d ≤ 109) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — saturation of color of each pencil.
Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".
6 3 10 7 2 7 7 4 2
YES
6 2 3 4 5 3 13 4 10
YES
3 2 5 10 16 22
NO
In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.
In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.
思路:
排序。从后往前扫一遍。考虑以每个点为最小值建堆是否合法。
对于当前点i,它需要至少k支铅笔,但是最大值不超过a[i]+d,
所以就会有一个成立的范围[l,r]。假设存在点k(l<=k<=r),
使得k+1这个位置建堆是合法的,那么点i建堆也是合法的。
用树状数组维护[l+1,r+1]中的建堆合法个数
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+7;
int dp[maxn],bit[maxn],righ[maxn];
int n,k,d,a[maxn];
void add(int i,int x)
{
while(i<=n+1)
{
bit[i]+=x;
i+=i&-i;
}
}
int sum(int i)
{
int ans=0;
while(i>0)
{
ans+=bit[i];
i-=i&-i;
}
return ans;
}
int main()
{
scanf("%d%d%d",&n,&k,&d);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
righ[i]=upper_bound(a+1,a+n+1,a[i]+d)-a;
add(n+1,1);
for(int i=n;i>=1;i--)
{
if(i+k-1<=n)
{
int is=sum(righ[i])-sum(i+k-1);
if(is>0)add(i,1);
}
}
if(sum(1))printf("YES\n");
else printf("NO\n");
return 0;
}