約瑟夫問題描述:編號為1~N的N個人圍順時針方向坐一圈,每人手持一個密碼(正整數),開始選一個正整數作為初始報數值m,從第一個人開始報數,報到第m個人時停止報數。報m的人出列,公布他手中的密碼作為新的m值,然后從下一個開始報數,直到所有人全部出列為止。
思路:該問題用循環鏈表的方法很容易解出,具體見如下代碼:
//==================================================================== // this program resolved a Josephus loop problem // Achieved by a loop-list // if you have any questions, welcome to chat with me // QQ:88521134 Email:88521134@qq.com //==================================================================== #include "stdafx.h" #include <iostream> using namespace std; typedef struct node { int data; node* next; }node; //======================================================================== // node* loop_create(int a[], int n): use an array to create a loop-list // int a[]: array // int n: the number of elements in the array //======================================================================== node* loop_create(int a[], int n) { int i; node *p,*q, *pre; pre = (node*)malloc(sizeof(node)); pre->data = a[0]; for (i=1; i<n; i++) { p = (node*)malloc(sizeof(node)); p->data = a[i]; if (i==1) pre->next = p; else q->next = p; q=p; } q->next = pre; return pre; } //==================================== // test program: Josephus Problem //==================================== int _tmain(int argc, _TCHAR* argv[]) { node* loopList = NULL; int a[5]={4,2,3,5,6}; int n = 5; int m = 7; int i; loopList = loop_create(a,5); // 創建一個循環鏈表 node *p=NULL; //下面開始循環取數 p=loopList; m%=n; while (p!=p->next) { for (i=1; i<m-1;i++) { p=p->next; } m=p->next->data; printf("%d", m); m%=(--n); p->next = p->next->next; p=p->next; } printf("%d\n",p->data); delete[]loopList; system("pause"); return 0; }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。