问题描述:
有一个数组a[N]顺序存放0~N-1,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数的原始下标位置。以8个数(N=7)为例:{0,1,2,3,4,5,6,7},0->1->2(删除)->3->4->5(删除)->6->7->0(删除),如此循环直到最后一个数被删除。
输入描述:
每组数据为一行一个整数n(小于等于1000),为数组成员数,如果大于1000,则对a[999]进行计算。
输出描述:
一行输出最后一个被删掉的数的原始下标位置。
这是典型的约瑟夫环问题,以下为实现代码:
#include <iostream>
#include <vector>
using namespace std;
void joseph(int count, int doom) {
int alive = count;
int number = 0;
int index = 0;
vector<int> vec(count , 1);
while (alive > 0) {
number += vec[index];
if (number == doom) {
if (alive == 1)
cout << index << endl;
vec[index] = 0;
--alive;
number = 0;
}
index = (index + 1) % count;
}
}
int main()
{
int n;
while (cin >> n) {
if (n > 1000)
n = 1000;
joseph(n, 3);
}
system("pause");
return 0;
}