Efficient optimization of a deformable template using dynamic programming