Menu Close

Find if it’s possible to distribute all the crayons into boxes and satisfy all the conditions.

Tina has received a gift of multicolored crayons for her birthday! Unfortunately, She 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 crayon.

Now Tina wants to put all the mess in the pack in order. She has an infinite number of empty boxes to do this. She would like to fill some boxes in such a way that:

Each crayon belongs to exactly one box;
Each non-empty box has at least k crayons in it;
If crayons 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 crayons i and j such that |ai - aj| ≤ d and they belong to different boxes.

Input:
The first line contains three integer numbers n, k and d — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of crayons in the same box, respectively.

The second line contains n integer numbers a1, a2, ..., an — saturation of color of each crayon.


Output:
Print the output "YES" if it's possible to distribute all the crayons into boxes and satisfy all the conditions. Otherwise print "NO".
#include <stdio.h>
#include <stdlib.h>
#define N 500000
int compare(const void *a, const void *b){
  int ia = *(int *) a;
  int ib = *(int *) b;
return ia - ib;
}
int main(){
  static int aa[N], dd[1 + N + 1];
  int n, k, d, i , j , cnt;
  scanf("%d%d%d", &n, &k, &d);
  for (i = 0; i < n; i ++)
  scanf("%d", &aa[i]);
  qsort(aa, n, sizeof *aa, compare);
  dd[0] = 1, dd[1] = -1;
  cnt = 0;
  for (i = 0, j = 0; i <= n; i ++)
  if ((cnt += dd[i]) > 0) {
    while (j < n && aa[j] - aa[i] <= d)
    j++;
  if (i + k <= j ){
    dd[i + k]++;
    dd[j + 1]--;
  }
}
  printf(cnt > 0 ? "\nYES\n" : "\nNO\n");
return 0;
}

INPUT_1:
6  2  3
4  5  3  13  4  10

OUTPUT:
YES


INPUT_2:
3  2  5
10  16  22

OUTPUT:
NO


ILLUSTRATION

EXECUTED USING gcc


Morae Q!