约瑟夫问题:给定n个人,每个人按顺时针顺序从1开始报数,报到m数的人出局,出局人的下一个人从1开始接着报数,依此循环,最后仅剩的一个人即为最幸运的人。
解决约瑟夫问题,即对给定的n和m,找出最幸运的人。
程序代码:
//约瑟夫问题
#include <iostream> #include <vector> using namespace std; void select(vector<int> v, int n, int m) { int c = -1; while (n >= 2) { for (int i = 0; i < m; i++) { c++; if (c == n - 1 && c != i) { c = -1; } if (c == n) { c = 0; } } vector<int>::iterator it = v.begin(); for (int j = 0; j < c; j++, it++){} cout<<"Delete "<<v[c]<<endl; *v.erase(it); c--; n--; } cout<<"The lucky one: "<<v[0]<<endl; } void main(int argc, char *args[]) { vector<int> v; int i, n, m; cin>>n>>m; for (i = 1; i <= n; i++) { v.push_back(i); } select(v, n, m); }
注:解决约瑟夫问题用循环链表会更加简单!
测试数据1:
8 3
测试结果1:
Delete 3
Delete 6
Delete 1
Delete 5
Delete 2
Delete 8
Delete 4
The lucky one: 7
Press any key to continue
测试数据2:
19 3
测试结果2:
Delete 3
Delete 6
Delete 9
Delete 12
Delete 15
Delete 18
Delete 2
Delete 7
Delete 11
Delete 16
Delete 1
Delete 8
Delete 14
Delete 4
Delete 13
Delete 5
Delete 19
Delete 10
The lucky one: 17