There are shirts in a row, numbered from to . Initially, they appear in the order from left to right. Shirt has color .
There are days. On day , you wear shirt . You pay a cost equal to its current position in the row, counting from at the left. You then remove this shirt and return it to either the left end or the right end. The other shirts keep their relative order, and the row again contains all shirts before the next day.
After the last day, all shirts of each color must occupy consecutive positions. The colors may appear in any order, and shirts of the same color may appear in any order within their block.
Choose the return end on every day to minimize the total cost while satisfying this final condition. Print the minimum total cost, or if no sequence of choices satisfies it.
Return the shirts to the right, right, left, and right ends, respectively. The daily costs are , and the final order is . The total cost is .
Return shirt to the right and shirt to the left. The final order is , with total cost .
The only shirt costs on each of the three days, for a total cost of .