prioritize_states() now actually sorts by weight.
The new algorithm also runs in linear time.