【问题描述】
编程求解约瑟夫问题:有n个小孩围成一圈,从1开始依次为他们编号。要求从第w个小孩开始报数,报到第s的小孩出列,然后从下一个继续报数,仍是报到第s的小孩出列,如此重复下去,直到所有的小孩都出列,求小孩的出列顺序。
【参考代码】
#include <stdio.h>
typedef struct
{
int next;
int flag;
}child;
int main()
{
int n, w, s, i = 0, j=0, next;
child c[100];
printf("请输入小孩子个数n w s:");
scanf("%d %d %d", &n, &w, &s);
next = w-1;
while (i < n-1)
{
c[i].flag = 0; c[i].next = i + 1; i++;
}
c[i].flag = 0; c[i].next = 0;
for (i = 0; i < n; i++)
{
j = 0;
while (j < s)
{
while (c[next].flag == 1) next = c[next].next;
j++;
if (j == s) break;
next = c[next].next;
}
c[next].flag = 1;
printf("%d ", next+1);
next = c[next].next;
}
return 0;
}