CP: The fewest rooms

A conference has n talks, each with a start and an end time. Two talks that overlap need different rooms, but a talk may start at the exact time another ends in the same room. Find the smallest number of rooms.

What to build

Put all start times in one sorted list and all end times in another. Go through the starts in order. If the earliest unfinished end time is at most this start, a room has been freed: reuse it. Otherwise a new room is needed.

Requirements

  • Sort the starts and the ends separately
  • Reuse a room when an end time is at most the new start

Input

The first line has n. Each of the next n lines has start end (start < end).

Output

The smallest number of rooms.

Constraints

1 ≤ n ≤ 100,000. Times are between 0 and 10⁹.

Example

Input:

4
1 4
2 5
4 6
7 8

Output:

2

Why it works

Rooms are needed only for talks that are running at the same moment. When a talk starts, if some earlier talk has already ended, one room can be reused; the earliest end time is the best one to reuse. Sorting both lists lets a single pointer track which ends have been used.

Examples

Example 1 · Input
4
1 4
2 5
4 6
7 8
Expected output
2
Example 2 · Input
3
1 10
2 3
3 4
Expected output
2

Hints

Hint 1

vector<int> s, e; sort both.

Hint 2

Keep j = 0 for the next unused end time. For each start s[i]: if e[j] <= s[i] then j++ (reuse), else rooms++.

Hint 3

Rooms start at 0, and the first talk always adds one because e[0] > s[0].

Solution

Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> s(n), e(n);
    for (int i = 0; i < n; i++) cin >> s[i] >> e[i];
    sort(s.begin(), s.end());
    sort(e.begin(), e.end());
    int rooms = 0, j = 0;
    for (int i = 0; i < n; i++) {
        if (e[j] <= s[i]) j++;
        else rooms++;
    }
    cout << rooms << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Sorting first, then greedy →