有n个人围成一圈,从第一个人开始报数(从1到3),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。c++
时间: 2023-12-23 21:27:12 浏览: 27
以下是使用C++解决这个问题的代码示例:
```cpp
#include <iostream>
#include <list>
int findLastPerson(int n) {
std::list<int> people;
for (int i = 1; i <= n; i++) {
people.push_back(i);
}
auto it = people.begin();
while (people.size() > 1) {
for (int i = 0; i < 2; i++) {
it++;
if (it == people.end()) {
it = people.begin();
}
}
it = people.erase(it);
if (it == people.end()) {
it = people.begin();
}
}
return *it;
}
int main() {
int n = 10; // 假设有10个人
int lastPerson = findLastPerson(n);
std::cout << "最后留下的是原来第" << lastPerson << "号的那位。" << std::endl;
return 0;
}
```