generic version of the beam search