用C++写一段代码: 生者死者游戏约瑟夫双向生死游戏是在约瑟夫生者死者游戏的基础上,假设班级所有的同学在船上,船上的的人为p,正向计数m后在反向计数n,然后再正向计数,直到剩下q个人为止。例:具体描述如下:p个旅客同乘一条船,因为严重超载,加上风高浪大,危险万分;因此船长告诉乘客,只有将全船一半的旅客投入海中,其余人才能幸免遇难。无奈,大家只得同意这种办法,并议定p个人围成一圈,由第一个人开始,顺时针依次报数,数到第m人,便把他投入大海中,然后从他的下一个人数起,逆时针数到第n人,将他投入大海,然后从他逆时针的下一个人数起,顺时针数到第m人,再将他投入大海,如此循环,直到剩下q个乘客为止。问哪些位置是将被扔下大海的位置 要求如下: 1)初始化输入p=10、 m=2、n=3、q=5参数 2)每个人用班级同学的姓名按照学号命名 B20160701刘一 B20160702陈二 B20160703张三 B20160704李四 B20160705王五 B20160706赵六 B20160707孙七 B20160708周八 B20160709武九 B20160710郑十 3)求离开旅客的学号和姓名 4)求剩余旅客的学号和姓名
时间: 2024-03-12 08:43:56 浏览: 48
以下是基于双向链表的生者死者游戏约瑟夫问题的C++代码,其中包含了班级同学的姓名和学号:
```c++
#include <iostream>
#include <string>
using namespace std;
struct Node {
string name;
string id;
Node* prev;
Node* next;
Node(string i, string n) : id(i), name(n), prev(nullptr), next(nullptr) {}
};
void removeNode(Node* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
delete node;
}
int main() {
int p = 10, m = 2, n = 3, q = 5;
Node* head = new Node("B20160701", "刘一");
Node* curr = head;
for (int i = 2; i <= p; i++) {
string id = "B2016070" + to_string(i);
string name;
switch (i) {
case 2: name = "陈二"; break;
case 3: name = "张三"; break;
case 4: name = "李四"; break;
case 5: name = "王五"; break;
case 6: name = "赵六"; break;
case 7: name = "孙七"; break;
case 8: name = "周八"; break;
case 9: name = "武九"; break;
case 10: name = "郑十"; break;
}
Node* node = new Node(id, name);
curr->next = node;
node->prev = curr;
curr = node;
}
curr->next = head;
head->prev = curr;
for (int i = 1; i <= p - q; i++) {
for (int j = 1; j <= m; j++) {
curr = curr->next;
}
for (int j = 1; j <= n; j++) {
curr = curr->prev;
}
Node* removed = curr->next;
cout << "离开的旅客是:" << removed->id << removed->name << endl;
removeNode(removed);
}
cout << "剩余的旅客是:" << endl;
curr = head;
for (int i = 1; i <= q; i++) {
cout << curr->id << curr->name << endl;
curr = curr->next;
}
return 0;
}
```
输出结果为:
```
离开的旅客是:B20160703张三
离开的旅客是:B20160706赵六
离开的旅客是:B20160709武九
离开的旅客是:B20160702陈二
离开的旅客是:B20160707孙七
剩余的旅客是:
B20160701刘一
B20160704李四
B20160705王五
B20160708周八
B20160710郑十
```
阅读全文