Build a directed graph with an edge for every command. Only the presence of a symbol matters, not its number of occurrences.
Call an absent symbol a hole. Initially there are no holes. Executing has three possible effects:
Thus holes are created but never destroyed, and they move against the edges. If the final holes form a set , our loss is .
Every vertex with an outgoing edge must be a hole at some moment: immediately after executing that edge, its source is absent. Conversely, whenever a vertex is a hole, we can execute all of its outgoing commands without changing anything.
So our task is to visit every vertex with outgoing edges using holes, while minimizing the total value of their final positions.