约瑟夫问题

约瑟夫问题

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

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

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

输入

输入n和m值。

输出

输出胜利者的编号。

示例输入

5 3

示例输出

4

提示

第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀
 
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 struct vode
 4 {
 5     int date;
 6     struct vode *next;
 7 };
 8 int main()
 9 {
10     int m,n;
11     scanf("%d%d",&m,&n);
12     struct vode *head,*tail,*p,*q;
13     p=(struct vode *)malloc(sizeof(struct vode ));
14     p->next=NULL;
15     p->date=1;
16     head=p;
17     tail=p;
18     int i;
19     for(i=2;i<=m;i++)
20     {
21         p=(struct vode *)malloc(sizeof(struct vode ));
22         p->date=i;
23         tail->next=p;
24         tail=p;
25         p->next=NULL;
26 
27     }
28     tail->next=head;
29     q=head;
30     while(q->next!=head)
31     q=q->next;
32     int sum=0;
33     int count=0;
34     while(q->next!=p)
35     {
36         p=q->next;
37         sum++;
38         if(sum%n==0)
39         {
40             q->next=p->next;
41             count++;
42         }
43         else q=p;
44     }
45     printf("%d
",q->date);
46     return 0;
47 }
View Code
原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/3264620.html