improved heuristic with precomputation