Joseph Ring is a mathematical application problem: known n individuals (denoted by number 1,2,3...N respectively) sit around a round table. From the person numbered K began to count, the number to m of the person out of the man, and his next person from 1 began to count, the number to m of the person again, according to this rule repeat until the round table all the people out. Ask for the number of the last person left.
#include "stdafx.h" #include <vector> #include <iostream>using namespace Std;template <class Inputiterator, Class distance>void advance (vector<int>& i, int n); Vector<int>::iterator do_once ( Vector<int> &cycle, vector<int>::iterator it, int m) {int k = Cycle.end ()-it-1;if (k >= m) {it = cycle. Erase (it + m); if (it = = Cycle.end ()) it = Cycle.begin (); return it;} Else{int h = m%cycle.size ()-k;if (h>0) {it = Cycle.erase (Cycle.begin () + m%cycle.size ()-k-1); if (it = = Cycle.end () ) it = Cycle.begin (); return it;} Else{it = cycle.erase (it + m%cycle.size ()); if (it = = Cycle.end ()) it = Cycle.begin (); return it;}} int Joseph_problem (int n, int k, int m) {_asserte (k <= n); Vector<int>cycle;vector<int>::iterator it;for ( int i = 0; I < n; i++) {cycle.push_back (i);} it = Cycle.begin (); Advance (it, k-1); while (Cycle.size ()! = 1) {it = Do_once (cycle, it, m-1);} return *it+1;} int _tmain (int argc, _tchar* argv[]) {/*VECTOR<INT>CYCLE;VECTOR<int>::iterator it;for (int i = 0; i < 4; i++) {cycle.push_back (i);} it = Cycle.begin (); Advance (it, 3), cout << * (IT) << endl;cout << * (Cycle.erase (IT)) << Endl;*/cout << 4 4 << endl;cout << Joseph_problem (4, 2, 5) << Endl;system ("pause"); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Joseph Ring Question