约瑟夫环问题
约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。求剩下最后的一个人的编号。
#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; }
版权声明: