Calendar
InterviewTime limit1sMemory limit512 MB
Place each schedule as high as possible on a 365-day calendar, group horizontally consecutive days into rectangles, and print the total coated area.
- Level
Medium6 of 10
- Topics
- Implementation, Sorting, Simulation, Greedy
- Solved
- No attempts yet
Problem
Suhyeon has a calendar whose days of the year are numbered from 1 to 365. Suhyeon is a very organized person, so she planned out the whole year and marked every schedule on the calendar.
As summer was ending, the rainy season began, and the dampness is about to erase the schedules marked on the calendar. To keep them from being erased, Suhyeon is going to attach coating paper to the calendar only where schedules are marked. But she found this too annoying, so she decided to follow these rules.
- If two consecutive days each have at least one schedule, the two schedules are called consecutive.
- All consecutive schedules must be contained in a single rectangle.
- She cuts coating paper the size of the smallest rectangle that encloses all consecutive schedules.
The calendar follows these rules.
- A schedule includes its start date and end date.
- Schedules are filled in one by one, starting with the one whose start date is earliest.
- If start dates are equal, the schedule with the longer duration is filled in first.
- A schedule is placed as high as possible.
- The height of one schedule is 1.
- The width of one day is 1.

Suppose schedules are given as in the figure above. The area of the coating paper is the blue region below.

Here the total coating paper size is 3 x 8 + 2 x 2 = 28.
Given the number of schedules and each schedule's start date and end date, find the area of coating paper that Suhyeon cuts.
Input
The first line gives the number of schedules N. (1 ≤ N ≤ 1000)
From the second line, N lines follow, each giving a start date S and an end date E. (1 ≤ S ≤ E ≤ 365)
Output
Print the area of the coating paper.