Three boxes of sliotars, three GAA club shops: where will the stock earn most?
You have three boxes of sliotars to share among three GAA club shops. Each shop can take all three, some, or none, and you have to send out every box. How should you split them to get the biggest total return?
Remember how you found the best route from each point by working backwards? Here, the table shows what each shop earns from zero, one, two or three boxes. Giving two to shop A earns eight euro. Whether that's a good choice depends on what the other shops can earn.
Start with three boxes. Watch one go to shop A. Now shop B has just two boxes left to work with. Each shop is a stage, and the number of boxes left when you reach that shop is the state.
Try a different choice. You start with three boxes and send two to shop A. When you reach shop B, what number goes in the state column? Pick the number that tells shop B what it has left to work with.
With s boxes left, try giving the shop k boxes, from zero up to s. Add today's return to the best return for the stock left. A worse continuation can't improve that total. That's Bellman's principle. For shortest paths in a directed acyclic network, minimise the edge weight plus the remaining distance.
Start at C. It must take every box that's left, so copy its returns. Then work back to B. With two boxes left, try giving B zero, one or two. Adding C's return gives four, seven or six euro. Record seven as the best total and one as B's choice.
At A, compare giving zero, one, two or three boxes. Add the best later return each time: nine, thirteen, twelve, nine. Thirteen wins, so A gets one. Follow the optimal policy, the best choice for each stage and state: with two left, B gets one, and C gets the last.
Now start with just two boxes and use the same return tables. Compare giving A zero, one or two boxes. Then follow the recorded choice at B for the stock you have left. Pick the best allocation in shop order, A, B, C.
A greedy rule takes the biggest immediate return at A, so A gets all three boxes for nine euro. If you maximise each shop's return separately, twenty-one euro looks better, but you'd need nine boxes. The backward table compares feasible choices and finds thirteen euro with just three boxes.
Work backwards from T: M is one away, so from S, three beats five. With Dijkstra, start at S. Settle M at two, the smallest tentative distance, and improve T to three. With undirected edges, going back to S cannot improve zero. Settle T and trace back through M.