PTA monkey king election (Josephus problem)

Subject description:

To choose a new group of monkeys Monkey King. Monkey new selection method is: N allow only the candidate circle monkeys, numbered sequentially starting from a certain number from 1 to N position. From the start countin No. 1, from 1 to report 3 per round, where the report of 3 monkeys to exit the circle, and from then immediately begin a monkey under the same number reported. So the cycle, the last remaining elected a monkey on Monkey King. Will the original resolution was elected a few monkey Monkey King?

Input formats:

On a single line to a positive integer N (≤1000).

Output formats:

Monkey King was elected in a row output number.

Sample input:

11

Sample output:

7

Analysis of ideas:

  1. This is a class Josephus problem. The circle size may create an array, and the initial value assigned to each monkey 1, when the monkeys report value becomes 0 3 Exit circle. This value changing process executed once, k is incremented by 1 when k == N-1, i.e. the number of outgoing k, the remaining number is 1, the game ends.
  2. And Josephus problem can be simplified to perform duplicate array from 0 to N-1 of. Add the determination condition in a cycle, the array element value of 0 is skipped. When the value is encountered element 1, if the statement is executed block by block in the statement count counting, when the count == 3, the value becomes 0, k ++, count counting again, becomes zero.
  3. When the cursor to the maximum array, the array is re-circulated, to be understood that an array head to tail, i.e. a ring, counted and the count is not affected, is still thought of as a number of packets ring contact.

Code:

#include <stdio.h>
int main()
{
	int N, i, count = 0, k = 0, flag = 0;
	//count计数作为报数,是否为3的判断。k计算出局人数,当人数剩余1即可结束。flag标记最后一只数值为1的猴子。 
	scanf("%d", &N);
	int n[N]; //创建一个与猴子人数相同的数组,每个元素代表一只猴子。 
	for(i = 0; i < N; i++)
		n[i] = 1; //当猴子仍参与报数游戏时,数值为1,当猴子出局后,数值为0,以此判断该猴子是否参与报数游戏。 
	while(k != N-1) //当k == N-1,即剩余人数为1,该猴子为大王,游戏结束。 
		for(i = 0; i < N; i++)
			if(n[i] == 1) //n[i]等于0的猴子,则跳过,不参与报数。 
			{
				flag = i; 
				count++; //每一只猴子报数,count加1。 
				if(count == 3) //当n[i]猴子报到count==3。 
				{
					n[i] = 0; //猴子出局。 
					k++; //出局人数加1。 
					count = 0; //count重新报数。 
				}	
			}
	//可以简单理解循环条件只是判断游戏是否继续,循环过程是重复for循环执行,即数组下标重复移动,头尾相接。 
	printf("%d", flag+1); //因为数组从0开始。 
	return 0;
}

Will explain in more detail, I feel good like this can be a lot of concerns

Released two original articles · won praise 2 · views 42

Guess you like

Origin blog.csdn.net/jenny_jack/article/details/104427998