##概述 约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知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; }