约瑟夫环有很多种解法,这里我提供一种数据结构,用队列来模拟。直接采用了STL里面队列的模板,看下面代码之前,跟我默念,STL大法好!!哈哈哈。
大致思路:先把所有人都放进队列里面,然后从1开始出队,1出队再进队,这样1就从队首到了队尾,就这么一直循环,如果到了第m个就只出队不让他进队。这样队列里面人数越来越少,到最后就出完了,代码如下:
#include<bits/stdc++.h>
using namespace std;
int n,m,cnt=1;
queue<int>q;
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++) q.push(i);
while(!q.empty())
if(cnt==m)
{
cnt=1;
cout<<q.front()<<" ";
q.pop();
}
else
{
q.push(q.front());
q.pop();
cnt++;
}
}