约瑟夫

/*问题描述:n个人(编号0~(n-1)),从0开始报数,报到m-1的退出,剩下的人继续从0开始报数。求胜利者的编号。*/


#include <stdio.h>  
int main(void)  
{  
  int n, m, i, s=0;  
  printf ("N M = ");  
  scanf("%d%d", &n, &m);  
  for (i=2; i<=n; i++)  
  s=(s+m)%i;  
  printf ("The winner is %d\n", s);  
  return 0 ;  
}  
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 struct stu
 4 {
 5     int num;
 6     struct stu *next;
 7 };    
 8 /*int shuzu(int n,int m)
 9 {
10     int a[302];
11     int i,t,p;
12     for(i=0;i<=n;i++)//数组初始化为1
13         a[i]=1;
14     t=n;
15     i=1;
16     p=1;
17     while(t>1)//当数组中还有超过一个未出圈就继续循环
18     {
19         if(a[i]==1)//判断是否出圈
20         {
21             if(p==m)//判断是否到达m个,是则初始化,否则计数加加
22             {
23                 a[i]=0;
24                 p=1;
25                 t--;
26             }
27             else
28                 p++;
29         }
30         i++;
31         if(i>n)  i=1;//判断是否超过数组长度,是则从头开始
32     }
33     for(i=1;i<=n;i++)//寻找最后一个未出圈的谁
34         if(a[i]==1)
35         printf("%d\n",i);
36         return 0;
37 }*/
38 
39 int main()
40 {
41     int i,n,m;
42     struct stu *p,*q,*head;//链表专用    
43     while(scanf("%d%d",&n,&m),n||m)
44     {
45     //    shuzu(n,m);//数组计数
46 
47 
48         //链表计数
49         head=(struct stu*)malloc(sizeof(struct stu));
50        head->num=1;
51        head->next=head;
52        p=head;
53        if(m==1)  printf("%d\n",n);
54        else
55        {
56           for(i=2;i<=n;i++)//生成链表
57           {
58                q=(struct stu*)malloc(sizeof(struct stu));
59                q->num =i;
60                p->next =q;
61                p=p->next ;
62                p->next=head;
63            } 
64           //q=head;
65           while(head!=head->next)//开始循环
66           {
67               for(i=2;i<m;i++)
68                   head=head->next ;
69                 head->next =head->next->next;
70                 head=head->next;
71           }
72           printf("%d\n",head->num);
73           free(head);
74        }
75     }
76     return 0;
77 }

 

posted @ 2013-04-18 13:06  萧凡客  阅读(170)  评论(0编辑  收藏  举报