LQ optimal control for a class of hybrid systems