【报数游戏】N个人围成一圈,给他们顺序编号,从1开始到N;他们从1开始依次报数,报到为M的人自动退出圈圈,然后下一个人接着从1开始报数;
直到剩余的人数小于M。请问最后剩余的人在原先的编号为多少?
#include <iostream>
#include<vector>
using namespace std;
void Count(int temppeople,int tempnum) {//(游戏人数,出圈数字)
vector<int> remain;
vector<int> ::iterator iter;
int temp = 0;
for (int i = 1; i <= temppeople; i++) {
remain.push_back(i);
}
while (remain.size() >= tempnum) {
for (iter = remain.begin(); iter != remain.end(); ) {
temp++;
if (temp%tempnum == 0) {
//cout << "删除元素:" << (*iter) << endl;
iter = remain.erase(iter);
}
else ++iter;
}
if (iter == remain.end()) {
iter = remain.begin();
}
//cout << "元素剩余为:";
//for (iter = remain.begin(); iter != remain.end(); iter++) {
// cout << *iter << " ";
//}
//cout << endl<<"当前大小:"<<remain.size()<<endl<<endl;
}
cout << "游戏结束,最终存活者编号:";
for (iter = remain.begin(); iter != remain.end(); iter++)
cout << *iter << " ";
cout << endl;
system("pause");
}
int main()
{
#pragma region 报数出圈
cout << "请输入参赛人数:";
int people = 50;
cin >> people;
cout << "请输入淘汰数字:";
int num;
cin >> num;
Count(people, num);
#pragma endregion
}
下面附上解除注释的运行截图
运行过程已经很明朗了。