1002. 猴子选大王(Version 2)
| ||
Description
猴子选大王,有N只猴子,从1~N进行编号。它们按照编号的顺时针方向,排成一个圆圈,然后从第一只猴子开始报数。第一只猴子报1,以后每只猴子报的数字都是它前面猴子所报数字加1。如果一只猴子报的数字是M,则该猴子出列,下一只猴子重新从1开始报数。剩下的猴子继续排成一个圆圈报数,直到全部的猴子都出列为止。最后一个出列的猴子胜出。
Input
The first line is an integer t, indicating the number of test cases. Then there are t lines and each line contains two positive integer N(0<N<=100) and M(0<M<=100).
Output
For each test case, print out the number of the Monkey King.
Sample Input
2 5 2 4 3
Sample Output
3 1 Problem Source: Lists, Stacks, and Queues |
约瑟夫环,用循环链表。
#include <iostream>
using namespace std;
struct monkey
{
int num;
monkey* next;
};
monkey *initial(int n)
{
monkey *list=new monkey;
monkey *p=list;
p->num=1;
p->next=NULL;
for(int i=2;i<=n;i++)
{
monkey *temp=new monkey;
temp->num=i;
temp->next=NULL;
p->next=temp;
p=temp;
}
p->next=list;
return list;
}
int main()
{
int t,n,m;
cin>>t;
while(t--)
{
cin>>n>>m;
if(m==1)
{
cout<<n<<endl;
continue;
}
monkey *circle=initial(n);
int count=1;
monkey *tempp;
while(circle->next!=circle)
{
if(count+1==m)
{
circle->next=circle->next->next;
circle=circle->next;
count=0;
}
else
{
tempp=circle;
circle=circle->next;
}
count++;
}
cout<<circle->num<<endl;
}
return 0;
}