Задание описано полностью вот тут http://www.cyberforum.ru/discrete-mathematics/thread627133.html#post3289488