Sherlock and Watson have mastered the intricacies of the language C++ 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.
N intervals are given, and the i
th interval is defined by the
inclusive endpoints [Li, Ri], where Li ≤ Ri.
The tutor defined the covered area of a set of intervals as the number of
integers appearing in at least one of the intervals. (Formally, an integer p
contributes to the covered area if there is some j such that
Lj ≤ p
≤ Rj.)
Now, Watson always likes to challenge Sherlock. He has asked Sherlock to remove exactly one interval such that the covered area of the remaining intervals is minimized. Help Sherlock find this minimum possible covered area, after removing exactly one of the N intervals.
Each test case consists of one line with eight integers N, L1, R1, A, B, C1, C2, and M. N is the number of intervals, and the other seven values are parameters that you should use to generate the other intervals, as follows:
First define x1
= L1 and y1
= R1. Then, use the
recurrences below to generate xi, yi
for i
= 2 to N:
xi
= ( A*xi-1
+ B*yi-1
+ C1 ) modulo M.yi
= ( A*yi-1
+ B*xi-1
+ C2 ) modulo M.
We define Li = min(xi, yi)
and Ri = max(xi, yi)
, for
all i
= 2 to N.
For each test case, output one line containing Case #x: y
, where x
is
the test case number (starting from 1) and y
is the minimum possible
covered area of all of the intervals remaining after removing exactly one
interval.
1 ≤ N ≤ 1000.
1 ≤ N ≤ 5 * 105(500000).
Input Output 3 Case #1: 0 1 1 1 1 1 1 1 1 Case #2: 4 3 2 5 1 2 3 4 10 Case #3: 9 4 3 4 3 3 8 10 10
In case 1, using the generation method, the set of intervals generated are: {[1, 1]}. Removing the only interval, the covered area is 0.
In case 2, using the generation method, the set of intervals generated are: {[2, 5], [3, 5], [4, 7]}. Removing the first, second or third interval would cause the covered area of remaining intervals to be 5, 6 and 4, respectively.
In case 3, using the generation method, the set of intervals generated are: {[3, 4], [1, 9], [0, 8], [2, 4]}. Removing the first, second, third or fourth interval would cause the covered area of remaining intervals to be 10, 9, 9 and 10, respectively.