#include<iostream>
#include <cstdlib>
#include <vector>
using namespace std;

// 定义链表节点结构体
typedef struct Lnode{
    int data;
    struct Lnode *next;
}LNode, *Linklist;

// 创建循环链表
void creatlist(Linklist &head,int n){
    head = new LNode;
    head->next = NULL;
    LNode *r = head;
    for(int i = 1; i <= n; i++){
        LNode *p = new LNode;
        p->data = i;
        p->next = NULL;
        r->next = p;
        r = p;
    }
    r->next = head->next; // 形成循环
}

// 模拟约瑟夫问题,支持多轮游戏
vector<int> josephus(Linklist &head, int n, int m, int numPasswords){
    vector<int> results; // 存储所有出列人员
    for(int j = 0; j < numPasswords; j++){
        LNode *p = head->next;
        LNode *q;
        int num = 0;
        while(num < n){
            for(int i = 1; i < m; i++){
                q = p;
                p = p->next;
            }
            results.push_back(p->data); // 记录出列人员
            q->next = p->next;
            delete p;
            p = q->next;
            num++;
        }
    }
    return results;
}

int main(){
    int n, m, numPasswords;
    cout << '请输入n,回车输入:';
    cin >> n;
    Linklist head = NULL;
    creatlist(head, n); // 创建初始循环链表
    cout << '请输入游戏遍数:' << endl;
    cin >> numPasswords;
    cout << '请输入m,回车输入:';
    cin >> m;
    vector<int> gameResults = josephus(head, n, m, numPasswords); // 获取游戏结果
    cout << '游戏结果:' << endl;
    for(int i = 0; i < gameResults.size(); i++){
        cout << gameResults[i] << ' ';
    }
    cout << endl; // 换行
    return 0;
}

原文地址: https://www.cveoy.top/t/topic/Roq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录