Josephus环

来源:互联网 发布:cms系统是什么 编辑:程序博客网 时间:2024/05/20 20:22

 

#include <stdio.h>
#include <stdlib.h>

struct Jew
{
 int number;
 struct Jew* next;
};

int main(int argc, char** argv)
{
 struct Jew* jew;
 struct Jew* r;
 int N;
 int M;
 int i;
 printf("Please input number of jew(N) and interval(M): \n");
 scanf("%d%d",&N,&M);
 jew = (struct Jew*)malloc(N* sizeof(struct Jew));
 r=jew;
 for(i=1;i<N;i++)
 {
  r->number=i;
  r->next=jew+i;
  r=r->next;
 }
 r->number=N;
 r->next=jew;

 printf("Suicide order: \n");
 while(r!=r->next)
 {
  for(i=0;i<(M-1);i++)
   r=r->next;
  printf("%4d",r->next->number);
  r->next=r->next->next;
 }
 printf("\n When N=%d and M=%d,Josephus,hiding in position %d survives.\n",N,M,r->number);
 free(jew);
 return 0;
}

 

0 0
原创粉丝点击