【数据结构算法】约瑟夫环问题(线性表)

这是我写的第一个博客,目前读大二,如果写的有问题还请各位多多指教~


众所周知,约瑟夫环问题是一个出现在计算机科学和数学中的问题据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从。首先从一个人开始,越过k-2个人(因为第一个人已经被越过),并杀掉第k个人。接着,再越过k-1个人,并杀掉第k个人。这个过程沿着圆圈一直进行,直到最终只剩下一个人留下,这个人就可以继续活着。问题是,给定了和,一开始要站在什么地方才能避免被处决?Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。

《【数据结构算法】约瑟夫环问题(线性表)》

以下是C语言实现:


//Demo for Joseph & List // // #include <stdio h=””> #include <stdlib h=””> #include <malloc h=””> #define LIST_INIT_SIZE 100 #define LIST_INCERMENT 10 #define OVERLOW 0 #define TRUE 1 #define ERROR 0 typedef int ElemType; typedef int Status; typedef struct { ElemType *elem; int length; int listSize; }Joseph, SqList; Status InitList_Sq(SqList *S) { S->elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(S->elem == NULL) { printf(“Failure to initial a new List\n”); exit(OVERLOW); } S->length = 0; S->listSize = LIST_INIT_SIZE; return TRUE; } Status ListEmpty_Sq(Joseph *S) { if(S->length == 0) { return TRUE; } else { return ERROR; } } Status ListInsert_Sq(SqList *S, int i, ElemType e) { //Incert element e in front location i //1 <= i <= ListLength_Sq(S) + 1 ElemType *newBase; int count; if((i < 1) || (i > (S->length + 1))) //Illegal i { return 0; } if(S->length >= S->listSize) { newBase = (ElemType*)realloc(S->elem,(S->listSize + LIST_INCERMENT) *sizeof(ElemType)); if(!newBase) { printf(“Failure to realloc\n”); return ERROR; S->elem = newBase; S->listSize += LIST_INCERMENT; } } for( count = S->length – 1; count >= i – 1; count–) { S->elem[count+1] = S->elem[count]; } S->elem[i-1] = e; S->length ++; return TRUE; } Status ListDelete_Sq(Joseph *S, int i) { int e; if(i<1 i=””>S->length) { return ERROR; } e = S->elem[i-1]; for(int count=i;count<s->length;count++) { S->elem[count-1] = S->elem[count]; } S->elem[S->length] = 0; S->length–; return e; } Status Input_M(int b){ int m; printf(“$ Which people depueue (出列): “); scanf(“%d”, &m); if(m <= 0){ printf(“Error,because m < 0\n”); Input_M(b); } else{ return m; } } Status Input_N() { int n; printf(“$ Total number(总人数): “); scanf(“%d”, &n); if(n<=0){ printf(“Error,because n < 0\n”); Input_N(); } else return n; } int main() { Joseph hoge; Joseph *S; S = &hoge; InitList_Sq(S); int n, m, e; n = Input_N(); m = Input_M(n); for(int i=0;i<=n;i++) ListInsert_Sq(S,i,i); int i = 1, t; while(!ListEmpty_Sq(S)) { i = i + m – 1; while(i>S->length) i = i-S->length; t = ListDelete_Sq(S,i); printf(“$ %5d号出列 \n\n”,t); } return 0; } </s-></1></malloc></stdlib></stdio>

菜鸟作品  多多指教

    原文作者:约瑟夫环问题
    原文地址: https://blog.csdn.net/WWH_19951122/article/details/49641767
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞