题解:P1996 约瑟夫问题

· · 题解

简单模拟题。

题意

有一个有 n 个人的数列,每隔 m 个淘汰一个,问你淘汰的顺序。

思路

其实只需要用一个循环队列模拟就行了,每一次循环 m,每次把都将队首弹出之后重新入队,根据队列先进先出的特性,最后剩下的就是要真真淘汰的,直接输出即可。

Code

用 STL 的队列模拟的。


#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,k;
    cin>>n>>k;
    queue<int>q;
    for(int i=1;i<=n;i++)q.push(i);
    while(!q.empty()){
        for(int i=1;i<k;i++){
            q.push(q.front());
            q.pop();
        }
        cout<<q.front()<<' ';
        q.pop();
    }
    return 0;
}