其他分享
首页 > 其他分享> > 围圈淘汰逃离死亡问题

围圈淘汰逃离死亡问题

作者:互联网

问题:

N个人一二三报数,报三的出去,余下重新报

代码

#include <iostream>

#define list_length 41
#define			  N	 3

namespace Myspace
{
	using std::cout;
	using std::endl;

	typedef struct node
	{
		int num;
		node* next;
		node* front;

	}node;

	node* InitList(int root_num = 0)
	{
		node* head = (node*)malloc(sizeof(node));
		node* p_node = head;

		if (head)
		{
			head->num = root_num;
			head->next = NULL;
			for (int i = 1; i < list_length; i++)
			{
				node* new_node = (node*)malloc(sizeof(node));
				if (new_node)
				{
					new_node->front = p_node;
					p_node->next = new_node;
					new_node->num = ++root_num;
					p_node = new_node;

					if (i == list_length - 1)
					{
						head->front = new_node;
						new_node->next = head;
						return head;
					}
					else { new_node->next = NULL; }
				}
				else { return NULL; }
			}
		}
		else { return NULL; }
	}

	int get_rest(int length = list_length, int n = N)
	{
		int res = 0;

		while (1)
		{
			if (0 == length / n) { res = length; break; }
			length = length - length / n;
		}
		return res;
	}

}

using namespace Myspace;

int main()
{
	int rest = get_rest();
	int temp = 0;
	node* p_temp = (node*)malloc(sizeof(node));
	node* List = InitList(1);
	int num = 1;

	for (int i = 0; i < 1000000; i++)
	{
		if (i > list_length && List->front->num > List->num) { cout << endl << endl; }

		temp = List->num;

		for (int j = 0; j < rest; j++) { p_temp = List->next; }

		if (p_temp->num == temp) { free(p_temp); break; }

		if (num == N)
		{
			List->front->next = List->next;
			List->next->front = List->front;
			List = List->next;
			num = 1;
		}
		else
		{
			cout << List->num << "\t" << num++ << endl;
			List = List->next;
		}
	}
	return 0;
}

标签:node,int,List,next,逃离,length,num,围圈,淘汰
来源: https://blog.csdn.net/qq_47750142/article/details/119218546