https://docs.google.com/document/d/1XsttooV5ZKU8KnFgKARvdzxHEZ1CmLG8dGY5YVAhfts/edit описание алгоритма тут