gpt4 book ai didi

c - 用链表求解 Josephus

转载 作者:行者123 更新时间:2023-11-30 19:22:19 24 4
gpt4 key购买 nike

我已经尝试了一段时间,但我不知道如何让下面的程序以 N 作为输入并生成 M ,以便最后死去的士兵是第 13 个(N>13);

 int main()
{
int N, M;
struct node { int player_id; struct node *next; };
struct node *p, *q;
int i, count;

printf("Enter N (number of players): "); scanf("%d", &N);
printf("Enter M (every M-th payer gets eliminated): "); scanf("%d", &M);

// Create circular linked list containing all the players:

p = q = malloc(sizeof(struct node));

p->player_id = 1;

for (i = 2; i <= N; ++i) {
p->next = malloc(sizeof(struct node));
p = p->next;
p->player_id = i;
}

p->next = q;//Close the circular linkedlist by having the last node point to the 1st

// Eliminate every M-th player as long as more than one player remains:

for (count = N; count > 1; --count) {
for (i = 0; i < M - 1; ++i)

p = p->next; p->next = p->next->next;

// Remove the eiminated player from the circular linked list.
} printf("Last player left standing is %d\n.", p->player_id);

return 0;
}

结果应该与 this 相同一个(但我需要它在链接列表中,因为我不明白那个):>.

最佳答案

我没有阅读上面的所有代码,我认为它可以找到给定 N 的最后一项和M

根据原问题,12<N<100 。所以,也许可以在给定的时间内通过暴力破解。

  • 您阅读了N
  • 开始循环查找m从 1
  • 在循环中:
    • 运行算法,使用循环变量 m 。如果最后一项是 13,则返回循环变量。

编辑:你不需要做很多工作。您只需开始一个循环,而不是阅读 M .

M=1;
while(1)
{
//your code goes here:
//build up the linked list with N element
//eliminate the nodes, until only one remains
//instead of writing out the last number, you check it: if it equals 13 print M, if doesn't, increment `M` and continue the loop.
if(p->player_id==13)
{
printf("The minimal M is: %d\n", M);
break;
}
else
M++;
}

如果您想对多个N执行此操作-s,你可以把这个循环放入一个函数中。在这种情况下,安装了打印 M ,该函数应该返回它。有趣的是:链表部分是你做的。也许你应该先尝试更简单的练习。

编辑2: HERE这是我的最终答案,检查结构和输出,我希望它是可以理解的。

注意:我认为如果你真的想学习,你应该做这样的事情,而不是陷入一个不平凡的问题:

  • 理解指针
  • 理解结构
  • 了解链表
  • 对链表的头/尾/某个位置进行插入/更新/删除
  • 10 分钟内自行解决 Josephus 问题

关于c - 用链表求解 Josephus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com