一、问题描述
二、算法分析
这是一个约瑟夫环问题,解法一:STL 库
- int JosephusProblem_Solution1(int n, int m)
- {
- if(n < 1 || m < 1)
- return -1;
- list<int> listInt;
- unsigned i;
- //初始化链表
- for(i = 0; i < n; i++)
- listInt.push_back(i);
- list<int>::iterator iterCurrent = listInt.begin();
- while(listInt.size() > 1)
- {
- //前进m - 1步
- for(i = 0; i < m-1; i++)
- {
- if(++iterCurrent == listInt.end())
- iterCurrent = listInt.begin();
- }
- //临时保存删除的结点
- list<int>::iterator iterDel = iterCurrent;
- if(++iterCurrent == listInt.end())
- iterCurrent = listInt.begin();
- //删除结点
- listInt.erase(iterDel);
- }
- return *iterCurrent;
- }
int main()
{
int total = 0;
cout << "Please input total number of people : ";
cin >> total;
int number = 0;
cout << "Please input selected number : ";
cin >> number;
/* If number = 3
* f(1) = 0
* f(2) = 1 = (f(1) + 3) % 2
* f(3) = 1 = (f(2) + 3) % 3
* f(4) = 0 = (f(3) + 3) % 4
* f(5) = 3 = (f(4) + 3) % 5
* ...
* f(n) = x = (f(n-1) + 3) % n
* */
int last = 0; // f(1) = 0
for(int i = 2; i <= total; ++i)
{
last = (last + number) % i;
}
cout << "The last one is : " << last + 1 << endl;
return 0;
}