約瑟夫問題

約瑟夫問題

Time Limit: 1000ms   Memory limit: 65536K  有疑問?點這裏^_^

題目描述

n個人想玩殘酷的死亡遊戲,遊戲規則如下:

n個人進行編號,分別從1到n,排成一個圈,順時針從1開始數到m,數到m的人被殺,剩下的人繼續遊戲,活到最後的一個人是勝利者。

請輸出最後一個人的編號。

輸入

輸入n和m值。

輸出

輸出勝利者的編號。

示例輸入

5 3

示例輸出

4

提示

第一輪:3被殺第二輪:1被殺第三輪:5被殺第四輪:2被殺

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    int n,m,i;
    struct node *head,*p,*q,*tail;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->data=i;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    tail->next=head->next;
    for(i=1,p=head;;i++,head->next=p)
    {
		if(n==1)break;
        if(i%m==0)
        {
            q=p->next;
            p->next=q->next;
            free(q);
			n--;
        }
		else p=p->next;
    }
    printf("%d",p->data);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章