您的位置:首页 > 其它

约瑟夫问题

2018-01-22 14:59 260 查看


约瑟夫问题

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic


Problem Description

n个人想玩残酷的死亡游戏,游戏规则如下:

n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。

请输出最后一个人的编号。


Input

输入n和m值。


Output

输出胜利者的编号。


Example Input

5 3



Example Output

4



Hint

第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀

01
#include
<stdio.h>
02
#include
<stdlib.h>
03
struct
node
04
{
05
int
data;
06
struct
node
*next;
07
};
08
int
main()
09
{
10
int
n,
m, i, j;
11
struct
node
*p, *q, *head;
12
head
= (
struct
node
*)
malloc
(
sizeof
(
struct
node));
13
head->next
= head;
14
scanf
(
"%d%d"
,
&n, &m);
15
q
= head;
16
17
for
(i
=0;i<n-1;i++)
18
{
19
p
= (
struct
node
*)
malloc
(
sizeof
(
struct
node));
20
p->data
= i+1;
21
q->next
= p;
22
q
= p;
23
p->next
= head;
24
}
25
head->data
= i + 1;
26
q->next
= head;
27
j
= n;
28
q
= head;i = 1;
29
while
(j>1)
30
{
31
if
(i%m==0)
32
{
33
p
= q->next;
34
q->next
= p->next;
35
free
(p);
36
j--;
37
}
38
else
39
{
40
p
= p->next;
41
q
= q->next;
42
}
43
i++;
44
}
45
printf
(
"%d\n"
,
q->data);
46
return
0;
47
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: