Monkey pick King question (Joseph Ring)

Source: Internet
Author: User
Tags printf

Reprint Please specify source: http://blog.csdn.net/u012860063


Question: M only monkeys to choose the King, the election method is as follows: All monkeys according to 1,2......N number in a circle, starting from the first sequence 1,2......m, usually reported in the exit ring of M, so loop off until only one monkey in the circle, this monkey is the king.


Joseph Ring question;

Backtracking: The total number of monkeys cycle, each cycle is the current need to circle the monkeys arranged to the end of the array. So all the monkeys cycle through (counterclockwise), the array of the head of the monkeys is the Monkey King. Notice that the loop together finds the first remaining array before it loops it. That is, for in the program (i = n-1; I >= 0; i--)


The code is as follows:

The first type:

#include <cstdio>
#define MAX
int n,m;
int Monkey[max];
void init ()
{for
	(int i = 0; i < n; i++)
		monkey[i]=i+1;
}
int main () 
{
	int i, j, K, T;
	while (~SCANF ("%d%d", &n,&m))
	{
		init ();
		for (i = n-1; I >= 0, i--)
		{for
			(k = 1; k <= m; k++)
			{
				t=monkey[0];
				for (j = 0; J < i; j + +)
				{
					monkey[j]=monkey[j+1];
				}
				monkey[i]=t;
			}
		}
		printf ("Monkey King is:%d monkeys \ n", monkey[0]);
	}
	return 0;
}

The second kind of recursion:

#include <cstdio>
int main ()
{
    int n, m;
    while (~SCANF ("%d%d", &n,&m))
    {
        int ans = 0;
        for (int i = 2; I <= n; i++)
        {
            ans = (ans+m)%i;
        }
        printf ("Monkey King is:%d monkeys \ n", ans+1);
    }
    return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.