約瑟夫問題
Time Limit: 1000ms Memory limit: 65536K 有疑問?點這裏^_^
題目描述
n個人進行編號,分別從1到n,排成一個圈,順時針從1開始數到m,數到m的人被殺,剩下的人繼續遊戲,活到最後的一個人是勝利者。
請輸出最後一個人的編號。
輸入
輸出
示例輸入
5 3
示例輸出
4
提示
#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;
}