Skip to content

Latest commit

 

History

History

Problem C

Problem C. Watson and Intervals

Problem

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 ith interval is defined by the inclusive endpoints [L, R], where L ≤ R.

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 LpR.)

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.

Input

Each test case consists of one line with eight integers N, L, R, A, B, C, C, 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 = L and = R. Then, use the recurrences below to generate for i = 2 to N:

  • = ( A* + B* + C ) modulo M.
  • = ( A* + B* + C ) modulo M.

We define L = and R = , for all i = 2 to N.

Output

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.

Limits

1 ≤ T ≤ 50.
0 ≤ LR ≤ 109.
0 ≤ A ≤ 109.
0 ≤ B ≤ 109.
0 ≤ C ≤ 109.
0 ≤ C ≤ 109.
1 ≤ M ≤ 109.

Small dataset

1 ≤ N ≤ 1000.

Large dataset

1 ≤ N ≤ 5 * 105(500000).

Sample

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.