有关约瑟夫环的介绍,可以参见百度百科的约瑟夫环。
程序中假定人数n小于100,输入数据为n和m。其中,n为人数,数到第m个人出局。输出出局人的顺序。输入数据为0和0时程序结束。
AC的C语言程序如下:
/* I00032 约瑟夫环(Joseph problem) */
#include <stdio.h>
#define MAXN 100
#define next(p, n) (p + n) % n + 1
int circle[MAXN+1];
int go(int start, int m, int n)
{
while(circle[start] == 0)
start = next(start, n);
while(--m) {
start = next(start, n);
while(circle[start] == 0)
start = next(start, n);
}
return start;
}
int main(void)
{
int n, m, residue, pa, i;
while(scanf("%d%d", &n, &m) != EOF) {
if(n == 0 && m == 0)
break;
for(i=1; i<=n; i++)
circle[i] = i;
residue = n;
pa = 1;
while(residue) {
pa = go(pa, m, n);
circle[pa] = 0;
printf("%3d", pa);
residue--;
}
printf("\n");
}
return 0;
}
程序运行实例:
5 2
2 4 1 5 310 3
3 6 9 2 7 1 8 5 10 4
0 0