Refactor cost functions to use type Cost, and let them depend on the subrange