Watson and Intervals (Large)
Time limit5sMemory limit512 MB
Generate N intervals from a recurrence, then find the minimum covered integer count after removing exactly one interval.
- Level
Medium7 of 10
- Topics
- Intervals, Sorting, Simulation, Implementation
- Solved
- No attempts yet
Problem
Sherlock and Watson have mastered the C++ language in their programming course, so they have moved on to algorithmic problems. In today's class, the tutor introduced the problem of merging one-dimensional intervals. intervals are given, and the -th interval is defined by the inclusive endpoints , where .
The tutor defined the covered area of a set of intervals as the number of integers that appear in at least one of the intervals. Formally, an integer contributes to the covered area if there is some such that .
Watson always likes to challenge Sherlock. This time he asked Sherlock to remove exactly one interval so that the covered area of the remaining intervals is as small as possible. Help Sherlock find this minimum possible covered area after removing exactly one of the intervals.
Input
The first line contains the number of test cases . Each of the next lines contains one test case.
Each test case is one line with eight integers , , , , , , , and . is the number of intervals, and the other seven values are parameters that you use to generate the remaining intervals, as follows.
First set and . Then use the recurrences below to generate and for to :
For every from 2 to , define and .
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1 and is the minimum possible covered area of all the intervals that remain after removing exactly one interval.
Constraints
- (500000)
Hint
In case 1, the generation method produces the single interval . Removing the only interval leaves a covered area of 0.
In case 2, the generated intervals are , , and . Removing the first, second, or third interval makes the covered area of the remaining intervals 5, 6, and 4, respectively.
In case 3, the generated intervals are , , , and . Removing the first, second, third, or fourth interval makes the covered area of the remaining intervals 10, 9, 9, and 10, respectively.