This page is still under construction.

Parts of this page are still being built. What you see may change.

Marbles

Time limit5sMemory limit512 MB

Summary
Pairs of matching colors sit on a line; join each pair with a non-crossing path above y=0 and minimize the total height.
Level

Medium7 of 10

Topics
Stack, Greedy
Solved
No attempts yet

Problem

A square grid holds 2n2n marbles. They are painted in nn colors with exactly two marbles of each color, and they sit at the coordinates (1,0),(2,0),…,(2n,0)(1, 0), (2, 0), \dots, (2n, 0), one marble per point.

For each color, draw one path that joins the two marbles of that color. A path is made of vertical and horizontal segments between grid points. No two paths may cross or touch each other. No path may cross the line y=0y = 0, and a path may touch y=0y = 0 only at the two marbles it joins, so the first and the last segment of every path is vertical.

Given the arrangement of the marbles, find the smallest height of a drawing that obeys these rules. When no such drawing exists the answer is -1. The height is the difference between the largest and the smallest yy coordinate over the points of the drawn paths.

Figure. With the marbles in the order red red blue yellow blue yellow, the drawing below has height 2. R is red, B is blue, and Y is yellow.

+-+ +---+
| | |   |
R R B Y B Y
      |   |
      +---+

Input

The first line contains the number of test cases TT. The first line of each test case contains nn, the number of colors. The next line contains the colors of the marbles from left to right, 2n2n words separated by spaces. Each color is a string of at most 10 lowercase English letters. Exactly nn different colors appear and each color appears exactly twice.

Limits

  • 1≤T≤501 \le T \le 50
  • 1≤n≤5001 \le n \le 500

Output

For each test case, print Case #x: followed by the smallest height, one test case per line. x is the test case number starting from 1. Print -1 instead of a height when no valid drawing exists.

Examples3

  1. Example 1

    Input
    4
    3
    red red blue yellow blue yellow
    3
    red blue yellow red blue yellow
    3
    red blue yellow blue yellow red
    3
    red red blue blue yellow yellow
    
    Expected output
    Case #1: 2
    Case #2: -1
    Case #3: 3
    Case #4: 1
    
  2. Example 2

    Input
    3
    1
    a a
    2
    a a b b
    2
    a b a b
    
    Expected output
    Case #1: 1
    Case #2: 1
    Case #3: 2
    
  3. Example 3

    Input
    2
    4
    b d a d c b c a
    4
    a b c d c d a b
    
    Expected output
    Case #1: 4
    Case #2: 4