very elegant solution for 251 (Div. 2) - C :)