`

猴王选举

J# 
阅读更多

n 个猴子参加猴王选举,按照 m 进行循环报数。数到 m 的猴子被淘汰,  直到剩余最后一个猴子变为大王。

#include "stdafx.h"
#include <stdio.h>
#include <iostream>

#define KICK  2
int findKing(int monkeyNum, int round)
{
	int *arr = (int*) malloc(sizeof(int) * monkeyNum);
	int count = 0;
	int i = 0;
	while(true)
	{
		// N step forward
		for(int j =0; j+1 <round; j++)
		{
			while(KICK == *(arr + i%monkeyNum))
			{
				i++;	
			}
			i++;
		}

		//make sure it's not kick out
		while(KICK == *(arr + i%monkeyNum))
		{
			i++;
		}

		//then kick out it
		if (KICK != *(arr + i%monkeyNum))
		{
			std::cout << "kick out:" << i%monkeyNum <<std::endl;
			*(arr + i%monkeyNum) = KICK;
			count ++;
			i++;
		}

		// if there is only one left
		// show it's position
		if (count + 1 == monkeyNum)
		{
			while(KICK == *(arr + i%monkeyNum))
			{
				i++;
			}
			return i%monkeyNum;
		}
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	std::cout << "the king is :" << findKing(100,4);
	int i;
	std::cin >>i;
	return 0;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics