您的位置:首页 > 其它

[链表]约瑟夫环问题 Josephus

2016-12-06 00:09 453 查看



本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。

问题源地址:

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Index/problemdetail/pid/1197.html

Problem Description

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

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

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

Input

整数 n, m

Output

胜利者的编号

My Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define L 100001

struct node                         //define struct
{
int data;
struct node *next;
};

struct node * create(int n);

int main(void)
{
struct node *head, *p, *q;
int n, m, num, count;

//input
scanf("%d %d", &n, &m);         //n nodes, m times to delete
head = create(n);               //create chain

p = head->next;                 //current node
q = p;                          //node before p
while(q->next != p)
q = q->next;

//delete node
count = 0;                      //count deleted numbers
num = 0;                        //judge if delete
while(count < n - 1)
{
p = q->next;
num++;                      //count
if(num % m == 0)
{
q->next = p->next;
free(p);
count++;
}
else
q = p;
}

//output
printf("%d\n", q->data);

return 0;
}

struct node * create(int n)
{
struct node * p, * q, *head;
int i;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
q = head;
for(i = 0;i < n;i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->data = i +  1;
p->next = NULL;
q->next = p;
q = p;
}
p->next = head-> next;          //modify the pointer of the tail node
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: