#include #include #include 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 josephus(Linklist &head, int n, int m, int numPasswords){ vector results; LNode *p = head->next; for(int j = 0; j < numPasswords; j++){ 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; vector passwordList(numPasswords); cout << "请输入每遍游戏的报数密码:" << endl; for(int i = 0; i < numPasswords; i++){ cin >> passwordList[i]; } vector gameResults = josephus(head, n, passwordList[0], numPasswords); cout << "游戏结果:" << endl; for(int i = 0; i < gameResults.size(); i++){ cout << gameResults[i] << ' '; } return 0; }

约瑟夫问题 C++ 实现:多轮游戏,动态队列输出

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

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