Initial version: TLE on test #3.
Second version - WA on test #51.
Code for problem 366E.