#P13452. [GCJ 2009 Finals] Marbles
[GCJ 2009 Finals] Marbles
题目描述
You have marbles on a square grid. The marbles are colored in different colors such that there are exactly marbles of each color. The marbles are placed at the coordinates , , ..., .
Your task is to draw a path for each color that joins the two marbles of that color. Each path should be composed of vertical or horizontal line segments between grid points. No two paths can intersect or touch each other. No path may cross the line. Each path can only touch the line at the position of the two marbles it is connecting, so the first and last line segment of each path must be vertical.
Given an arrangement of marbles, return the minimum height of a solution, or return -1 if no solution exists. The height is defined as the difference between the highest and lowest Y-coordinates of the paths used.
An example:
red red blue yellow blue yellow
One solution would be:
+---+ +-----------+
| | | |
red red blue yellow blue yellow
| |
+-----------+
The minimum height is in this case.
输入格式
The first line of input gives the number of cases, . test cases follow. The first line of each case contains , the number of different colors for the marbles. The next line contains a string of words separated by spaces which correspond to the colors of the marbles, in order from left to right. Each color is a string of lower case letters ('a' .. 'z') no longer than 10 characters. There will be exactly different colors and each color will appear exactly twice.
输出格式
For each test case, output one line containing "Case #: ", where is the case number (starting from 1), followed by the height of any optimal solution, or -1 if no solution exists.
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
Case #1: 2
Case #2: -1
Case #3: 3
Case #4: 1
提示
Limits
Small dataset(7 Pts)
- Time limit:
303 seconds.
Large dataset(32 Pts)
- Time limit:
606 seconds.