C++约瑟夫问题
作者:野牛程序员:2023-08-10 15:39:06 C++阅读 2841
约瑟夫问题是一个经典的数学问题,描述如下:n个人(编号从1到n)围坐在一圈,从编号为1的人开始,每次数m个人,数到m的人出列,然后下一个人继续从1开始数,直到剩下最后一个人。
在C++中,可以使用循环链表来模拟解决约瑟夫问题。以下是一个简单的实现示例:
#include <iostream>
#include <list>
using namespace std;
int josephus(int n, int m) {
list<int> people;
// 初始化人员列表
for (int i = 1; i <= n; ++i) {
people.push_back(i);
}
auto current = people.begin();
while (!people.empty()) {
for (int i = 1; i < m; ++i) {
++current;
if (current == people.end()) {
current = people.begin();
}
}
cout << "Person " << *current << " is out." << endl;
current = people.erase(current);
if (current == people.end()) {
current = people.begin();
}
}
return *current;
}
int main() {
int n = 7; // 总人数
int m = 3; // 数到m的人出列
int survivor = josephus(n, m);
cout << "The last survivor is person " << survivor << endl;
return 0;
}在这个例子中,使用了C++的list容器来模拟围坐的人员列表,然后按照约瑟夫问题的规则,依次将人员出列,直到只剩下最后一个人。
请注意,这只是一个简单的示例,实际应用中可能还需要考虑更多的边界情况和优化。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

