A Double-Loop Algorithm to Minimize the Bethe and Kikuchi Free Energies