猴子选大王

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<=1000) and M(0<M<=10000).

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

#include<iostream>
using namespace std;

struct Node
{
	Node* next;
	int data;
};

Node* Create(int n)
{
	Node* head = new Node;
	Node*p, *pre;
	head->next = NULL;
	head->data = 1;
	pre = head;
	for (int i = 2; i <= n; i++)
	{
		p = new Node;
		p->data = i;
		p->next = NULL;
		pre->next = p;
		pre = p;
	}
	pre->next = head;
	return head;
}

void ChooseKing(Node* h, int M)
{
	int count;
	while (h->next != h)
	{
		count = 1;
		while (count<M-1 )
		{
			h = h->next;
			count++;
		}
		Node*q = h->next;
		h->next = h->next->next;
		h = h->next;
		delete q;
	}
	cout << h->data << endl;
	delete h;
}

int main()
{
	int m;
	cin >> m;
	while (m-->0)
	{
		int n, M;
		cin >> n >> M;
		Node*h = Create(n);
		ChooseKing(h, M);
	}

	return 0;
}
posted @ 2016-09-26 19:53  KennyRom  阅读(486)  评论(0编辑  收藏  举报