The Josephus Game
Given n player sitting in a circle, and a number m.
A hot potato starts at player 1, and is passed around m times.
The player holding the potato then is eliminated, the next
player gets the potato, and the game continues until only one
player is left.
1
#include<stdio.h>
2
#include<malloc.h>
3
typedef struct LinkList
4
{
5
int date;
6
struct LinkList *next;
7
}LNode;
8
int main()
9
{
10
int n,m,i;
11
LNode *L,*p,*q;
12
while(scanf("%d%d",&n,&m))
13
{
14
L=(LNode*)malloc(sizeof(LNode));
15
L->date=n;
16
L->next=L;
17
for(i=n-1;i>0;i--)
18
{
19
p=(LNode*)malloc(sizeof(LNode));
20
p->date=i;
21
p->next=L->next;
22
L->next=p;
23
}
24
p=L;
25
for(i=1;i<=m+1&&p->next!=p;i++)
26
{
27
if(i==m+1)
28
i=1;
29
if(i==m)
30
{
31
printf("%d\n",p->next->date);
32
q=p->next;
33
p->next=p->next->next;
34
free(q);
35
}
36
else
37
p=p->next;
38
}
39
printf("%d\n",p->date);
40
free(p);
41
}
42
return 0;
43
}
#include<stdio.h>2
#include<malloc.h>3
typedef struct LinkList4
{5
int date;6
struct LinkList *next;7
}LNode;8
int main()9
{10
int n,m,i;11
LNode *L,*p,*q;12
while(scanf("%d%d",&n,&m))13
{14
L=(LNode*)malloc(sizeof(LNode));15
L->date=n;16
L->next=L;17
for(i=n-1;i>0;i--)18
{19
p=(LNode*)malloc(sizeof(LNode));20
p->date=i;21
p->next=L->next;22
L->next=p;23
}24
p=L;25
for(i=1;i<=m+1&&p->next!=p;i++)26
{27
if(i==m+1)28
i=1;29
if(i==m)30
{31
printf("%d\n",p->next->date);32
q=p->next;33
p->next=p->next->next;34
free(q);35
}36
else37
p=p->next;38
}39
printf("%d\n",p->date);40
free(p);41
}42
return 0;43
}


浙公网安备 33010602011771号