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;
}