假设正在游玩约瑟夫游戏,从你开始报数,游戏规则与课上讲述一致,现在你想确保你是最后一个出列的玩家,如果由你设置m(即每报几个数出列一人),你应该如何设置m来确保自己的胜利?如何在确保时间复杂度,计算的开销等因素下,尽量进行优化的选取。可以通过所附的代码进行你所设想算法的验证。
要求
#include<iostream>
using namespace std;
enum boolean { FALSE, TRUE };
#define DefaultSize 100
template<class T>
class Vector
{
private:
T* elements;
int ArraySize, VectorLength;
void GetArray(void);
public:
Vector(int Size = DefaultSize);
~Vector(void) { delete[] elements; }
T Getnode(int i)
{
return(i < 0 || i >= VectorLength) ? NULL : elements[i];
}
boolean Insert(T& x, int i);
boolean Remove(int i);
};
template<class T>
void Vector<T>::GetArray(void)
{
elements = new T[ArraySize];
if (elements == NULL) { cerr << "Memory Allocation Error" << endl; }
}
template<class T>
Vector<T>::Vector(int sz)
{
if (sz <= 0)
cerr << "Invalid Array Size" << endl;
else
{
ArraySize = sz;
VectorLength = 0;
GetArray();
}
}
template<class T>
boolean Vector<T>::Insert(T& x, int i)
{
if (VectorLength == ArraySize)
{
cerr << "overflow" << endl; return FALSE;
}
else if (i<0 || i>VectorLength)
{
cerr << "position error" << endl; return FALSE;
}
else
{
for (int j = VectorLength - 1; j >= i; j--)
elements[j + 1] = elements[j];
elements[i] = x;
VectorLength++;
return TRUE;
}
}
template<class T>
boolean Vector<T>::Remove(int i)
{
if (VectorLength == 0)
{
cerr << "Vector is empty" << endl; return FALSE;
}
else if (i<0 || i>VectorLength - 1)
{
cerr << "position error" << endl; return FALSE;
}
else
{
for (int j = i; j < VectorLength - 1; j++)
elements[j] = elements[j + 1];
VectorLength--;
return TRUE;
}
}
void Josephus(Vector<int>& P, int n, int s, int m)
{
int k = 1;
for (int i = 0; i < n; i++) { P.Insert(k, i); k++; }
int s1 = s;
for (int j = n; j >= 1; j--)
{
s1 = (s1 + m - 1) % j;
if (s1 == 0) s1 = j;
int w = P.Getnode(s1 - 1);
P.Remove(s1 - 1);
P.Insert(w, n - 1);
}
}
int findM(int n, int s)
{
/////////////////////////////////////////////////
// Code here
/////////////////////////////////////////////////
}
int main(void)
{
int n, s, m;
cout << "Input total number, start index" << endl;
cin >> n >> s;
m = findM(n, s);
Vector<int> P(n);
Josephus(P, n, s, m);
cout << "The index of last member is:" << endl;
cout << P.Getnode(n - 1) << " ";
return 0;
}
1)基于附件代码所完成的代码;2)word文档一份,简述你的设计思路,并说明为什么觉得这个设计合理。