c语言约瑟夫生死问题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
原始问题:每30个乘客同乘一艘船,因为严重超载,加上风高浪大,危险万分,因此船长告诉乘客,只有将全船一半乘客投入海中,其余人才能幸免于难。
无奈,大家只得同意这种办法,并议定30个人围成一圈,由第1个人数起,依次报数,数到第9人,便把他投入大海中,然后再从他的下一个人数起,数到第9人,再将他扔到大海中,如此循环地进行,直到剩下15个乘客为止。
问哪些位置是将被扔下大海的位置。
改进:对于指定总人数,存活人数,扔下海的号码求解问题
循环链表求解代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Status int
#define success 1
#define fatal 0
#define ElemType int
#define Max 1000
typedef struct node{
ElemType data;
struct node *next;
}ListNode,*ListNodePtr;
typedef ListNodePtr List,*ListPtr;
Status cirList_Create(ListPtr L,ElemType elem[],int n){
Status status=success;
ListNodePtr p,q,head;
int i=n-1;
q=(ListNodePtr)malloc(sizeof(ListNode));
q->next=NULL;
p=(ListNodePtr)malloc(sizeof(ListNode));
if(!p){status=fatal;}
p->data=elem[i];
head=p;
q->next=p;
i=i-1;
while(i>=0){
p=(ListNodePtr)malloc(sizeof(ListNode));
if(!p){status=fatal;break;}
p->data=elem[i];
p->next=q->next;
q->next=p;
i=i-1;
}
head->next=p;
(*L)=head;
return status;
}
int main(){
int i,j,m,N,K;
printf("分别输入总人数,留在船上人数,扔下海的号码:\n");
scanf("%d %d %d",&m,&N,&K);
int a[Max]={0};
for(i=0;i<m;i++){
a[i]=i+1;
}
List L;
ListNodePtr p,q;
cirList_Create(&L,a,m);
p=L;
printf("扔下海的位置:");
for(j=0;j<(m-N);j++){
for(i=1;i<K;i++)
p=p->next;
q=p->next;
p->next=q->next;
printf("%d ",q->data);
free(q);
}
i=0;
printf("\n安全位置:");
while(i<N){
printf("%d ",p->data);
p=p->next;
i++;
}
system("pause");
return 0;
}。