problems / 108

Fewest Clips to Cover the Match

medium intervals greedy sorting 2000 ms · 256 MB

Fewest Clips to Cover the Match

A broadcaster recorded n candidate clips of a match that ran from minute 0 to minute T. Clip i covers the closed interval of footage [l_i, r_i].

The editor wants to stitch together a set of clips so that every moment of the match, from 0 to T, is shown by at least one chosen clip. Chosen clips may overlap, and two of them may also simply meet end-to-end at a single instant (the moment is covered by whichever clip includes it as an endpoint) — the only thing that is not allowed is a moment covered by none of the chosen clips.

Find the minimum number of clips needed to cover [0, T] completely, or report that it cannot be done.

Input

The first line contains two integers n and T (1 ≤ n ≤ 2·10^5, 1 ≤ T ≤ 10^9).

Each of the next n lines contains two integers l_i and r_i (0 ≤ l_i ≤ r_i ≤ T) describing clip i. A clip may have l_i = r_i (it covers only a single instant).

Output

Print the minimum number of clips whose union covers [0, T], or -1 if no selection of clips covers all of [0, T].

Notes

In the first example, no clip other than the one starting at minute 0 covers minute 0, so it must be used; after that the editor should jump to whichever available clip reaches the furthest, not simply the first one that overlaps. Three clips suffice (for instance minutes [0,2], [2,7] and [7,9]), and no pair of clips can reach from 0 all the way to 9.

In the second example minute 0 to 2 and minute 3 to 5 can be covered, but nothing reaches across the gap between minute 2 and minute 3, so the answer is -1.

Example 1

Input

6 9
0 2
1 4
3 6
6 8
7 9
2 7

Output

3

Example 2

Input

3 5
0 2
3 5
2 2

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

Think of a moving frontier: the footage covered so far ends at some minute, and a clip can be used only if it starts no later than that minute. Among the clips that are usable right now, which one is worth picking?

Hint 2

Sort the clips by their start. Repeatedly take the usable clip that reaches furthest, count it, and move the frontier to its end, stopping once the frontier reaches T. A clip starting exactly at the frontier still joins up, and you must detect when no clip extends the frontier.

report an issue Prefer your own editor? sooks prep 108 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.