约瑟夫问题c++代码
时间: 2023-11-06 07:05:34 浏览: 53
约瑟夫问题是一个经典的问题,它的描述如下:有n个人围成一圈,从第一个人开始报数,报到m的人出圈,然后从出圈的下一个人开始重新报数,直到剩下最后一个人。现在我们来看一下C++代码实现:
```
#include <iostream>
#include <list>
using namespace std;
int main()
{
int n, m;
cout << "请输入总人数n和报数m:";
cin >> n >> m;
list<int> people;
for (int i = 1; i <= n; i++)
{
people.push_back(i);
}
list<int>::iterator it = people.begin();
while (people.size() > 1)
{
for (int i = 1; i < m; i++)
{
it++;
if (it == people.end())
{
it = people.begin();
}
}
it = people.erase(it);
if (it == people.end())
{
it = people.begin();
}
}
cout << "最后留下的人是:" << people.front() << endl;
return 0;
}
```
这段代码使用了STL中的list容器来存储人员编号,每次报数时,使用迭代器来遍历list容器,找到需要出圈的人员,并将其从list容器中删除。最后,list容器中只剩下最后一个人员,即为最终结果。