Many thanks to author of this task and Oleg Strekalovsky [Vologda SPU] for the hint ( http://acm.timus.ru/forum/thread.aspx?id=22536&upd=634614144741133716 ). PS. It is very unexpectedly to me that some collection types (e.g. HashMap) take so much memory and CPU time in java :-/