1. 程式人生 > 實用技巧 >1018 Public Bike Management (30分)(Dijkstra路徑儲存fa[]+DFS路徑搜尋)

1018 Public Bike Management (30分)(Dijkstra路徑儲存fa[]+DFS路徑搜尋)

13個人圍成一圈,從第1個人開始順序報號1,2,3。凡報到3者退出圈子。找出最後留在圈子中的人原來的序號。要求用連結串列實現。

解題思路:

建立一個環形連結串列,給連結串列中的每一個節點從1~13編號,然後開始淘汰過程,對於淘汰的節點,序號置為0,淘汰完成之後,找到序號不為0的即為最後留下的。

#include <stdio.h>
#define NUM 13
typedef struct people
{
	int num;
	struct people *next;
} people;

int main()
{
	int count = NUM;
	people p[NUM];
	people *head;
	head = p; //head 指向p[0]
    //1~13編號
	for (int i = 0; i < NUM; i++)
	{
		head->num = i + 1;
		head->next = &p[i + 1];
		head = head->next;
	}
    //最後一個元素指向第一個元素 , 形成環
	p[NUM - 1].next = p; 

	int i = 1;
	head = p;
	while (count > 1)
	{
        //跳過已經被淘汰的節點
		if (head->num == 0)
		{
			head = head->next;
			continue;
		}
		if (i == 3)
		{
            //被淘汰的節點,num置為0
			printf("第 %d 位置被淘汰\n", head->num);
			head->num = 0;
			count--;
		}
		head = head->next;
		i++;
		if (i > 3)
		{
			i = 1;
		}
	}
	printf("--------------\n");
	while (head->num == 0)
	{
        //非0節點即為最後留下的
		head = head->next;
		if (head->num != 0)
		{
			printf("留到最後的是 %d \n", head->num);
		}
	}

	return 0;
}

執行截圖: