глянь вот здесь http://www.stratum.ac.ru/textbooks/modelir/lection26.html, в самом конце описан алгоритм