问题描述:

约瑟夫问题:有n只猴子,按顺时针方向围成一圈选大王(编号从1到n),从第1号开始报数,一直数到m,数到m的猴子退出圈外,剩下的猴子再接着从1开始报数。就这样,直到圈内只剩下一只猴子时,这个猴子就是猴王,编程求输入n,m后,输出最后猴王的编号。

每行是用空格分开的两个整数,第一个是 n, 第二个是 m ( 0 < m,n <=300)。最后一行是:
0 0

输出:

对于每行输入数据(最后一行除外),输出数据也是一行,即最后猴王的编号。

:

1 6 2
2 12 4
3 8 3
4 0 0

样例输出:

1 5
2 1
3 7

代码:

 1 #include<stdio.h>                                                                                                                                                                                           
 2 #include<stdlib.h>
 3 typedef struct monkey{
 4     int val;
 5     struct monkey *next;
 6 }mon;
 7 mon *create(int num){  //创造链表
 8     mon *head=(mon*)malloc(sizeof(mon));
 9     head->next=NULL;
10     mon *pre=head;
11     for(int i=1;i<=num;i++){
12         mon *p=(mon*)malloc(sizeof(mon));
13         p->next=NULL;
14         pre->next=p;
15         pre=p;
16         p->val=i;
17     }
18     pre->next=head->next;
19     return pre;
20 }
21 int sel(mon *head,int cur,int m){  //提猴子
22     if(head->next==head)
23         return head->val;
24     if(cur<m)
25         return sel(head->next,cur+1,m);
26     else{
27         head->next=head->next->next;
28         return sel(head,1,m);
29     }
30 }
31 int main()
32 {
33     int m,n;
34     while(1){
35         scanf("%d%d",&n,&m);
36         if(n==0)
37             break;
38         mon *head=create(n);
39         int num=sel(head,1,m);
40         printf("%d\n",num);
41     }
42     return 0;
43 }

 

posted on 2017-11-25 22:51  宵夜在哪  阅读(224)  评论(0编辑  收藏  举报