Cavity algorithms under global constraints: classical and quantum problems