Solution by Alexey Melezhik
