A solution for Highload Cup 2018

Disclaimer

All code from the solution was written for the Cup requirements and will not work in real programs. Do not use any fragments in real programs as is!!!