死亡游戏(链表)

来源:互联网 发布:统计贸易数据自查报告 编辑:程序博客网 时间:2024/05/01 00:25

Description

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

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

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

Input

输入n和m值。

Output

输出胜利者的编号。

Sample Input

5 3

Sample Output

4
(亲自敲的,最后本是p->shu,但输出比实际值大1,我百思不得其解,改成p->shu-1,抱着试试的态度交了,没想到过了!!!这让我万思不得其解。)

代码:

#include <stdio.h>#include <stdlib.h>struct si{    int shu;    int biao;    struct si *next;}*head;int main(){    struct si *p,*q;    int n,m,i;    scanf("%d %d",&n,&m);    head=(struct si *)malloc(sizeof(struct si));    head->next=NULL;    head->shu=1;    head->biao=1;    q=head;    for(i=2; i<=n; i++)    {        p=(struct si *)malloc(sizeof(struct si));        p->shu=i;        p->biao=1;        q->next=p;        p->next=NULL;        q=p;    }    int k=1;    p=head;    int jl=0;    while(p!=NULL)    {        if(p->next->biao==1)        {            p=p->next;            k++;            if(k==m)            {                p->biao=0;                k=0;                jl++;            }        }        else            p=p->next;        if(jl==n)  break;        if(p->next==NULL)        {  if(head->biao==1)            q=head;            else            {q=head->next;            while(q->biao==0)                q=q->next;}            p=q;            k++;            if(k==m)            {                p->biao=0;                k=0;                jl++;            }        }    }    printf("%d",p->shu-1);    return 0;
还有神代码来解此题(但是不太懂):
  神代码
   
 #include <stdio.h>int main(){    int n, m, i, sl= 0;    scanf("%d%d", &n, &m);    for (i = 2; i <= n; i++)    {        sl= (sl+ m) % i;    }    printf ("%d\n", sl+1);    return 0;}






0 0
原创粉丝点击