Description
你听说过约瑟夫问题吗?问题大致如下:首先n个人围成一个圈,标记为1到n号。接着,从1号开始报数(从1开始),然后2号报数,然后3号。。。当有人报到到m时,这个人就要踢出比赛,然后从被踢出的人的下一个人开始,重新报数(从1开始)。这样经过n-1次后,就只剩下了一个人,问最后剩下的那个人是几号?
Input
第1行为T,表示有T组数据;
第2行到第T+1开始,每行输入n和m,n表示有几个人,m为上述的每报数m次就要踢出一个人
1=<n<=100, 1=<m<=100
Output
一个数,表示最后剩下了几号
Sample Input
2
5 3
6 4
Sample Output
4
5
AC代码
#include<stdio.h>
#include<stdlib.h>
struct node
{
int x;
struct node *next;
};
int main()
{
int t,n,m;
struct node *head,*tail,*p,*p1,*p2;
scanf("%d",&t);
while(t>0)
{
scanf("%d%d",&n,&m);
head=tail=NULL;
int i=1;
while(i<=n)
{
p=(struct node *)malloc(sizeof(struct node));
p->x=i;
if(head==NULL)
{
head=p;
}
else
{
tail->next=p;
}
tail=p;
i++;
}
if(m==1)printf("%d\n",n);//每一个都要删的时候直接输出最后一个数
else
{
i=1;
tail->next=head;
p2=head;
while(p2->next!=p2)
{
p1=p2;
p2=p2->next;
i++;
if(i==m)
{
p1->next=p2->next;
free(p2);
p2=p1->next;
i=1;
}
}
printf("%d\n",p2->x);
}
t--;
}
return 0;
}