Moving Cups Across Three Trays
Time limit1sMemory limit128 MB
Cups of sizes 1..n sit stacked (largest on top) on three trays; with moves allowed only between A-B and B-C, find the minimum number of moves to gather every cup onto A or C, or report -1 if more than m are needed.
- Level
Hard8 of 10
- Topics
- BFS, Dynamic programming, Simulation, Implementation
- Solved
- No attempts yet
Problem
There are cups, all of different sizes, and three trays A, B, and C. The cups are stacked in piles on the trays. On every tray the smallest cup is at the bottom, the second-smallest sits on top of it, the third-smallest on top of that, and so on — the cups are stacked upside down from smallest to largest. Hence the topmost cup on a tray is the largest cup on that tray.
The right side of the figure below shows a state with cups stacked 2, 0, and 3 on trays A, B, and C respectively.

Given the initial arrangement of the cups, we want to find the minimum number of moves needed to gather all cups onto either tray A or tray C while obeying the following rules 1–3.
- (Rule 1) Each move relocates exactly one cup: the topmost cup of a tray (that is, its largest cup).
- (Rule 2) You may not place a smaller cup on top of a larger one. In other words, a moved cup may be placed only on an empty tray or on top of a cup smaller than itself.
- (Rule 3) A single cup may be moved directly only from A to B, B to A, B to C, or C to B. Moving a cup directly from A to C, or from C to A, is not allowed.
Given the initial arrangement of the cups and an integer , write a program that decides whether all cups can be gathered onto a single tray (A or C) in at most moves. If it is possible, output the minimum number of moves; otherwise output -1.
Input
The first line contains and separated by a space (, ). The second, third, and fourth lines describe trays A, B, and C respectively. Each line begins with an integer giving the number of cups on that tray, followed by the sizes of those cups in ascending order. The sizes are the integers from to partitioned among the three trays, each size appearing exactly once.
Output
Print, on a single line, the minimum number of moves needed to gather all cups onto tray A or tray C. If this cannot be done in at most moves, print -1.