约瑟夫问题:n个骑士编号1,2,…,n,围坐在圆桌旁。编号为1的骑士从1开始报数,报到m的骑士出列,然后下一个位置再从1开始报数,找出最后留在圆桌旁的骑士编号。
(1)编写一个函数模板。以一种顺序容器的类型作为模板参数,在模板中使用指定类型的顺序容器求解约瑟夫问题。m,n是该函数模板的形参。
程序参考的输入(数字前为提示文字):
Input n and m:7 3
程序参考的输出:
Result:4
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
int Joseph(int n,int m)
{
T v;
//vector<int>::iterator t;
for(int i=1;i<=n;i++)
{
v.push_back(i);
}
int start = 0;
//t = v.begin();
while(v.size()!=1)
{
start = (start+m-1)%v.size();
//cout << start << endl;
v.erase(v.begin()+(start));
}
return v[0];
}
int main()
{
int n,m;
cout << "Input n and m:";
cin >> n >> m;
int t = Joseph<vector<int>>(n,m);
cout << "Result:" << t << endl;
return 0;
}