All problems

Problem 246

Minimum Arrows to Burst Balloons

Medium · 20 pts · Array, Greedy, Sorting

Problem

Balloons are spread along a wall, and each one covers a horizontal range [start, end]. An arrow shot straight up at position x bursts every balloon with start <= x <= end, and keeps flying. Find the minimum number of arrows needed to burst all the balloons. Sort the balloons by their end. Shoot the first arrow at the end of the first balloon; it bursts every balloon that starts at or before that point. The next balloon that starts after it needs a new arrow, shot at its end, and so on. Coordinates can reach the 32-bit limits, so be careful with overflow when comparing.

Input

First line: N. Next N lines: start and end of a balloon.

Output

Print the minimum number of arrows.

Constraints

1 <= N <= 100000; -2^31 <= start <= end <= 2^31 - 1

Example input

4
10 16
2 8
1 6
7 12

Example output

2

Explanation

An arrow at x = 6 bursts [1, 6] and [2, 8], since 6 lies in both. An arrow at x = 12 bursts [7, 12] and [10, 16]. One arrow cannot reach all four balloons, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Non-Overlapping Meetings Next: Boats to Save People