Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92058
  • 博文数量: 41
  • 博客积分: 866
  • 博客等级: 准尉
  • 技术积分: 282
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-22 22:49
文章分类

全部博文(41)

文章存档

2011年(41)

我的朋友

分类: C/C++

2011-11-26 18:11:52

约瑟夫生者死者游戏 的大意是 : 30 个旅客同乘一条船,因为严重超载, 加上风高浪大,
危险 万分;因此船长告诉乘客,只有将全船一半的旅客投入 海中 ,其余人才能幸免遇难。无
奈,大家只得同意这种办法,并议定 30 个 人 围成一圈,由第一个人开始,依次报数,数到 第
9 人,便把他投入大海中,然后从他的下一个人数起,数到第 9 人,再将他投入大海,如此
循环,直到剩下 15 个乘客为止。问哪些位置是将被扔下大海的位置。

 仅供参考,大家都比我聪明,还有更好的算法大家自己开发

#include "malloc.h"
#include "stdio.h"


#define MAXSIZE 30
typedef struct game
{
   int PeopleNo;
   struct game *next;
}game;

game* InitGame()
{
   int i=0;
   game *q,*p,*r;
   r=q=(game*)malloc(sizeof(game));
   if(q==NULL)
   {
        printf("分配数据链表头失败!\n");
        return NULL;
   }
   q->next=NULL;
   q->PeopleNo=1;

   for(i=2;i<=MAXSIZE;i++)
   {
       p=(game*)malloc(sizeof(game));
      if(p==NULL)
      {
           printf("分配数据链表头失败!\n");
           return NULL;
       }
      p->next=NULL;
      p->PeopleNo=i;
      q->next=p;
      q=p;
     }
   p->next=r;

   return r;
 
}

 

int LookDeath(game *q)
{
    int i=0;
    int count=0;
    game *s1,*s2;
    s1=q;
   while(s1)
   {

       for(i=1;i<9;i++)
       {
            s2=s1;
            s1=s1->next;//q的指针向前走8步
            // printf("%d  ",q->PeopleNo);
       }
  
       printf("%d  ",s1->PeopleNo);
       s2->next=s1->next;
       free(s1);
       s1=s2->next;
       count++;
      if(count==15)
      break;
    }

 return 0;
}

int main()
{
 int i=0;
 game *list,*s;
 list=InitGame();
 LookDeath(list);
 
 for(i=0;i<15;i++)
 {
  s=list->next;
  free(list);
  list=s;

 }
};

运行结果

死亡人数的号码为:

9 18 27 6 16 26 7 19 30 12 24 8 22 5 23

阅读(1252) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~