#K37432. Minimal Number of Stacks

    ID: 25975 Type: Default 1000ms 256MiB

Minimal Number of Stacks

Minimal Number of Stacks

You are given m books with various heights. Your task is to group all the books into stacks such that each stack has at least k books and the difference between the smallest and the largest book in the same stack does not exceed d. Formally, if a stack contains books with heights \(h_1, h_2, \dots, h_l\) (after sorting the heights in non-decreasing order), then it must satisfy \(l \ge k\) and \(h_l - h_1 \le d\). If it is impossible to group all books under these constraints, output -1.

Note: Books can be rearranged arbitrarily before grouping.

inputFormat

The input is given via standard input (stdin) and consists of two lines:

  1. The first line contains three space-separated integers: m (the number of books), d (the maximum allowed height difference within a stack), and k (the minimum number of books required in a stack).
  2. The second line contains m space-separated integers representing the heights of the books.

outputFormat

Output a single integer on standard output (stdout): the minimal number of stacks required if it is possible to group all the books under the rules described, or -1 if no valid grouping exists.

## sample
6 3 2
2 5 3 7 2 8
3