标签:josephus
约瑟夫环
约瑟夫环是一个古老的问题,它起源于一个犹太故事。据说,古代著名历史学家Josephus经历过如下故事:
在罗马人占领桥塔帕特之后,39个犹太人和Josephus以及他的一个朋友躲在一个山洞里面。39个犹太人决定宁死不让罗马人抓到,所以他们决定执行一个死亡游戏。
41个人组成一个圈,由第一个人开始报数,每报到3,那么这个人将自杀。然后由下一个人重新开始报数,直到所有人都自杀为止。
然后,Josephus和他的朋友并不想遵从,越是Josephus让他的朋友先假意答应,然后把他和朋友安排的16和31个位置,从而逃过了这场死亡游戏。
#include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef struct stuff { int index; struct stuff *next; }stuff; stuff* sl_create(int size) { stuff *p_list ; stuff *tempHeader; p_list = tempHeader = (stuff *)malloc(sizeof(stuff)); p_list->index = 1; int i = 2; for(; i <= size; i++) { stuff* ele = (stuff *)malloc(sizeof(stuff)); ele->index = i; ele->next = NULL; tempHeader->next = ele; tempHeader = ele; } return p_list; } stuff *getNextNotNullNode(stuff *node, stuff *header) { if(node->next == NULL) { return header; }else { return node->next; } } int main() { int maxPeople = 0; int m = 0; int remains = 5; printf("please input people and sp: \n"); scanf("%d", &maxPeople); scanf("%d", &m); printf("max people: %d, m %d \n", maxPeople, m); //构造链表数据结构 stuff* p_list = NULL; p_list = sl_create(maxPeople); /* do { printf("index= %d \n", p_list->index); p_list = p_list->next; }while(p_list != NULL); */ stuff *tempHeader = p_list; int count = maxPeople - remains; while(count > 0) { int i = 1; while(i < m-1) { printf("i= %d \n", i); p_list = getNextNotNullNode(p_list, tempHeader); i++; } if (p_list->next == NULL) { printf("kill %d\n", tempHeader->index); tempHeader = tempHeader->next; } else if(p_list->next->next == NULL) { printf("kill %d\n", p_list->next->index); p_list->next = NULL; } else{ printf("kill %d\n", p_list->next->index); p_list->next = p_list->next->next; } //下一人开始数数 p_list = getNextNotNullNode(p_list, tempHeader); /* if (p_list->next == NULL) { p_list = tempHeader; } else { p_list = p_list->next; } */ count --; } while(tempHeader != NULL) { printf("remain %d \n", tempHeader->index); tempHeader = tempHeader->next; } return 0; }
本文出自 “www.bogo.com” 博客,请务必保留此出处http://483181.blog.51cto.com/473181/1925738
标签:josephus
原文地址:http://483181.blog.51cto.com/473181/1925738