約瑟夫環問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重復下去,直到圓桌周圍的人全部出列。編程思路:先建立一個循環鏈表,找到第一個報數的人,依次列出出列人的序號。#include <iostream>using namespace std;struct Node{ int id; Node *next; Node(int i) { id = i; next = NULL; }};struct LinkedList{ Node *head; int length; LinkedList(){ head = NULL; length = 0; }};/************************************************************************//* n 為總人數 *//* k 為第一個開始報數的人 *//* m 為出列者喊到的數 *//************************************************************************/void Josephus(int n, int k, int m){ if (n<0||k<0||m<0) { cout << "三個輸入參數必須都為正整數" << endl; return; } if (n < k) { cout << "起始序號必須大于總人數" << endl; return; } //先建立循環鏈表 LinkedList *list = new LinkedList(); Node *node = list->head; Node *pnode = list->head; //先驅節點 for (int i = 1; i <= n; i++) { if (i == 1) { node = new Node(i); list->head = node; list->length++; node->next = node; } else { pnode = node; node = new Node(i); pnode->next = node; node->next = list->head; list->length++; } } //打印下,驗證現有鏈表信息正確 Node *temp = list->head; for (int i = 1; i <= n; i++) { cout << temp->id << ends; temp = temp->next; } cout << endl; node = list->head; pnode = list->head; //找到第一個開始報數的人 while (--k) { pnode = node; node = node->next; } cout << "第一個開始報數的人的id:" << node->id << endl; int j = m - 1; cout << "出列人的id依次是:" << ends; while (n--) { for (j = m-1; j > 0; j--) { pnode = node; node = node->next; } cout << node->id << " " << ends; pnode->next = node->next; node = pnode->next; }}void main(){ Josephus(5, 3, 1); cout << endl; Josephus(5, 3, 2); cout << endl; Josephus(9, 2, 3);}
|
新聞熱點
疑難解答
圖片精選