洛谷P1996 约瑟夫问题【链表】

题目:https://www.luogu.org/problemnew/show/P1996

题意:

约瑟夫环。每次取出第m个,第2m个......

思路:

链表维护。【感觉很少有用到链表。】非常经典的约瑟夫问题,用链表解决。

#include<cstdio>
#include<cstdlib>
#include<map>
#include<set>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath> 
#include<stack>
#include<queue>

#define inf 0x7fffffff
using namespace std;
typedef long long LL;
typedef pair<string, string> pr;

int n, m;
const int maxn = 105;
struct node{
    int id;
    int nxtid;
}nodes[maxn];

int main()
{
    scanf("%d%d", &n, &m);
    nodes[0].nxtid = 1;
    for(int i = 1; i <= n; i++){
        nodes[i].id = i;
        nodes[i].nxtid = i + 1;
    }
    nodes[n].nxtid = 1;
    
    bool fst = false;
    int now = 0, prev = 0;
    while(n--){
        for(int i = 0; i < m; i++){
            prev = now;
            now = nodes[now].nxtid;
        }
        if(fst)printf(" ");
        else fst = true;
        printf("%d", nodes[now].id);
        nodes[prev].nxtid = nodes[now].nxtid;
    }
    
    
    return 0; 
}

猜你喜欢

转载自www.cnblogs.com/wyboooo/p/10788845.html