约瑟夫问题猴子选大王

 1 /*
 2    功能Function Description:     约瑟夫问题--猴子选大王
 3    开发环境Environment:          DEV C++ 4.9.9.1
 4    技术特点Technique:
 5    版本Version:
 6    作者Author:                   可笑痴狂
 7    日期Date:                      20120801
 8    备注Notes:
 9    题目来源:            
10         http://poj.grids.cn/practice/2746
11 */
12 
13 /*
14 //代码一(递推法)
15 #include<stdio.h>
16 
17 int main()
18 {
19     int n,m,i;
20     int a[310];
21     a[1]=0;
22     while(scanf("%d%d",&n,&m),n||m)
23     {
24         for(i=2;i<=n;++i)
25             a[i]=(a[i-1]+m)%i;
26         printf("%d\n",a[n]+1);
27     }
28     return 0;
29 }
30 */
31 
32 //代码二(用链表)
33 #include<iostream>
34 using namespace std;
35 
36 struct node
37 {
38     int num;
39     node *next;
40 };
41 
42 void init(node *circle,int n)
43 {
44     node *r,*s;
45     circle->num=1;
46     circle->next=NULL;
47     r=circle;
48     for(int i=2;i<=n;++i)
49     {
50         s=new node;
51         s->num=i;
52 //        s->next=r->next;
53         r->next=s;
54         r=s;
55     }
56     r->next=circle;
57 }
58 
59 void solve(node *circle,int n,int m)
60 {
61     node *r,*s;
62     r=circle;
63     for(int i=1;i<n;++i)       //循环n-1次
64     {
65         for(int j=2;j<m;++j)
66             r=r->next;
67         s=r->next;
68         r->next=s->next;
69     //    delete s;             //这点不知道为啥删除之后剩下最后两个节点的时候运行时间会出错 提交显示runtime error,
70                               //不删除的话能AC 不知道为啥 ---求解
71         r=r->next;
72     }
73     cout<<r->num<<endl;
74 }
75 
76 int main()
77 {
78     int n,m;
79     node circle;
80     while(cin>>n>>m,n||m)
81     {
82         if(m==1)
83         {
84             cout<<n<<endl;
85             continue;
86         }
87         init(&circle,n);
88         solve(&circle,n,m);
89     }
90     return 0;
91 }
功不成,身已退
原文地址:https://www.cnblogs.com/dongsheng/p/2618587.html