Painting a Fence (Large)

Pick the fewest offers from N interval-and-color proposals so every one of 10000 fence sections is covered using at most 3 distinct colors.

Hard8IntervalsGreedyDynamic programmingImplementationNo attempts yetTime limit10sMemory limit512 MB

Problem

You need to hire painters for a fence. The fence has 10000 contiguous sections, numbered 1 to 10000.

Painters send you offers. One offer is a proposal to paint a contiguous block of sections in a single color. Accept a set of offers so that both of these hold:

  • Every section of the fence is painted.
  • At most 3 colors are used to paint the fence.

If both can hold, find the minimum number of offers you have to accept. Only the colors of the accepted offers count. Accepted offers may paint overlapping sections.

Input

  • One line with an integer TT, the number of test cases.

Each test case is given as follows.

  • One line with an integer NN, the number of offers.
  • NN lines, one per offer, each in the format C A B. CC is the color, an uppercase string of at most 10 letters. AA is the first section and BB is the last section the painter would paint, with 1AB100001 \le A \le B \le 10000.

Limits

  • 1T501 \le T \le 50
  • 1N3001 \le N \le 300

Output

For each test case print one line, in input order, holding Case #X: Y, where XX is the case number and YY is the minimum number of offers you have to accept. If there is no acceptable set of offers, print Case #X: IMPOSSIBLE.

Hint

In the first test case of the example input, accepting both offers paints the whole fence, 5000 sections each, with no overlap.

In the second case the painters overlap, which is acceptable.

In the third case accepting all four offers would cover the whole fence, but it would use 4 different colors, so that set is not acceptable.

In the fourth case section 4001 cannot be painted.

In the fifth case the first and second offers alone paint the whole fence.