Yandex Interview Question

Very hard algorithm contest at yandex