zoukankan      html  css  js  c++  java
  • 猴子选大王

    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;
    }
  • 相关阅读:
    MongoDB插入时间不正确的问题
    json 字符串转换成对象,对象转换成json字符串
    sqlServer sa用户登陆失败的解决办法
    基于web工作流开发
    javascript ajax的语法
    收藏和设为首页的方法
    asp.net收藏和设为首页的代码
    设计模式
    设计模式
    设计模式
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5910439.html
Copyright © 2011-2022 走看看