Optimised and safe version of `intersection`, and specialised function for computing all costs.