##概述 約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n我的(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號爲k的人開始報數,數到m的那我的出列;他的下一我的又從1開始報數,數到m的那我的又出列;依此規律重複下去,直到圓桌周圍的人所有出列。一般解決這類問題時咱們把編號從0~n-1,最後結果+1即爲原問題的解。node
##解法 ###模擬法ios
#include<stdio.h> #include<stdlib.h> struct_Node { int data; struct_Node*next; }; typedef struct_Node node_t; typedef struct_Linklist { node_t*phead; node_t*ptail; int len; }Linklist; staticnode_t*GetNode(inti)//新建並初始化節點 { node_t*pNode; pNode=(node_t*)malloc(sizeof(node_t)); if(!pNode) { printf("Error,thememoryisnotenough!\n"); exit(-1); } pNode->data=i; pNode->next=NULL; return pNode; } voidinit_list(Linklist*plist)//用第一個節點初始化循環單鏈表 { node_t*p; p=GetNode(1); //printf("TheNewNodeis:%d\n",p->data);//****TEST**** plist->phead=p; plist->ptail=p; p->next=plist->phead; plist->len=1; } static void Create_List(Linklist*plist,intn)//把其他數據添加到循環單鏈表中 { int i=0; node_t*pNew; for(i=2;i<=n;i++) { pNew=GetNode(i); /********TEST******** printf("TheNewNodeis:%d\n",pNew->data); ********TEST********/ plist->ptail->next=pNew; plist->ptail=pNew; pNew->next=plist->phead; plist->len++; } printf("Completesthee-waycirculationchaintablethefoundation!\n"); } voidPrint_List(Linklist*plist)//輸出鏈表內容 { node_t*pCur=plist->phead; do { printf("The%dperson.\n",pCur->data); pCur=pCur->next; }while(pCur!=plist->phead); printf("ThelengthoftheList:%d\n",plist->len); } 約瑟夫迴環函數實現 voidjoseph(Linklist*plist,intm)//約瑟夫迴環函數實現 { node_t*pPre=plist->ptail; node_t*pCur=plist->phead; int i; while(plist->len!=1) { i=0; while(i<m-1) { pPre=pPre->next; i++; } pCur=pPre->next; pPre->next=pCur->next; free(pCur); plist->len--; } printf("Thelastoneis:%d\n",pPre->data); } int main() { int n=0; printf("Please input the Length of the Circlelist:"); scanf("%d",&n); int m=0; printf("Please input the Stoppoint:"); scanf("%d",&m); LinklistpList; init_list(&pList); Create_List(&pList,n); Print_List(&pList); joseph(&pList,m); return 0; }
###數學法函數
#include <iostream> #include <list> using std::cout; using std::endl; using std::cin; using std::list; int main() { int total = 0; cout << "Please input total number of people : "; cin >> total; int number = 0; cout << "Please input selected number : "; cin >> number; /* If number = 3 * f(1) = 0 * f(2) = 1 = (f(1) + 3) % 2 * f(3) = 1 = (f(2) + 3) % 3 * f(4) = 0 = (f(3) + 3) % 4 * f(5) = 3 = (f(4) + 3) % 5 * ... * f(n) = x = (f(n-1) + 3) % n * */ int last = 0; // f(1) = 0 for(int i = 2; i <= total; ++i) { last = (last + number) % i; } cout << "The last one is : " << last + 1 << endl; return 0; }