1002. 猴子选大王(Version 2)

1002. 猴子选大王(Version 2)
 
     
     
 
Time Limit: 1sec    Memory Limit:256MB
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
 Copy sample input to clipboard
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;
}


			


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值