实现代码如下所示:
1 // 18_1.cc 2 #include <iostream> 3 #include <list> 4 using namespace std; 5 6 int josephus(size_t n, size_t m) { 7 if (n < 1 || m < 1) 8 return -1; 9 else if (n == 1) 10 return 0; 11 12 list<int> jos; 13 for(size_t i = 0; i < n; i++) 14 jos.push_back(i); 15 16 list<int>::iterator it = jos.begin(); 17 while(jos.size() > 1) { 18 for(size_t i = 1; i <= m; i++) { 19 it++; 20 if(it == jos.end()) // 模拟环形 21 it = jos.begin(); 22 } 23 24 list<int>::iterator next = it; 25 26 if (it == jos.begin()) 27 it = jos.end(); 28 it--; 29 jos.erase(it); 30 it = next; 31 } 32 33 return *it; 34 } 35 36 int main() { 37 size_t n = 10; 38 size_t m = 2; 39 cout << "The last one is: " << josephus(n, m) << endl; 40 return 0; 41 }
实现代码如下所示:
1 // 18_2.cc 2 #include <iostream> 3 using namespace std; 4 5 int josephus(size_t n, size_t m) { 6 if (n < 1 || m < 1) 7 return -1; 8 9 int res = 0; 10 for (int i = 2; i <= n; i++) 11 res = (res + m) % i; 12 13 return res; 14 } 15 16 int main() { 17 size_t n = 10; 18 size_t m = 2; 19 cout << "The last one is: " << josephus(n, m) << endl; 20 return 0; 21 }
IT公司100题-18-圆圈中最后剩下的数字,布布扣,bubuko.com
原文:http://www.cnblogs.com/dracohan/p/3904801.html