【问题标题】:Solving Josephus with linked lists用链表求解 Josephus
【发布时间】:2013-06-01 17:28:29
【问题描述】:

我已经尝试了一段时间,但我无法弄清楚如何让下面的程序以 N 作为输入并生成一个 M,以便最后一个死去的士兵是 13th(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 相同(但我需要它在链表中,因为我不明白那个):>。

【问题讨论】:

  • 如果有人想看问题,就在这里:bit.ly/JTeFaW
  • 是的,伙计,这就是我用我的语言从一本书中翻译出来的问题,看起来像是抄袭了那本书
  • 约瑟夫斯问题有一个封闭形式的解决方案。无需编写所有这些代码。

标签: c data-structures linked-list josephus


【解决方案1】:

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

根据原来的问题,12&lt;N&lt;100。所以,大概可以在给定的时间限制内简单地用蛮力解决。

  • 你读过N
  • 开始循环以从 1 中查找 m
  • 在循环中:
    • 运行算法,使用循环变量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 分钟内自己解决约瑟夫问题

【讨论】:

  • 是的,这是我的猜测,但实际上我不知道如何启动该循环,因为我是新手,而链表对我来说很痛苦。
  • @RediRedi 我试图解释它,你现在应该继续尝试。
  • @RediRedi 这是一个很好的解决方案 - 去吧。只需执行检查所有可能 M 值的循环,当它给你 13 时,得到循环当前的值
  • @pivovarit 是的,我修复了一个我刚刚将您的更改应用到我以前的代码的问题再次感谢......虽然看到我需要打印所有消除,如 1,8,14...... ....13 如何做到这一点
  • @RediRedi 该死的,我已经得到了你的答案;)如果你想打印消除,只需在删除元素之前在循环中插入一个打印语句
猜你喜欢
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2016-03-18
  • 1970-01-01
  • 2012-08-22
相关资源
最近更新 更多