古代某法官要判决n个犯人死刑,他有一条荒唐的逻辑,将犯人首尾的相接排成圆圈,然后从第s个人开始数起,每数到第m个犯人,就拉出来处决;然后又数m个,数到的犯人又拉出来处决,依次类推。剩下的最后一人可以豁免。
int main(int argc, char **argv)
{
int n = 10, s = 7, m = 3, count = 0, idx;
char person[10];
memset(person, '1', sizeof(person)); // '1' show live '0'show die
int i;
for(i=0;i<10;i++)
printf("%c ",person[i]);
printf("\n");
//first time
idx = (s-1-1+m);
person[idx] = '0';
n--;
while( n > 1 )
{
for(; ;)
{
if(idx > 9)
idx %= 10;
if(person[idx] == '1')
{
idx++;
count++;
if(count % 3 == 0)
break;
}
else
idx++;
}
person[idx-1] = '0';
n--;
}
for(i=0;i<10;i++)
printf("%c ",person[i]);
exit(0);
}
本文展示了一个通过C语言实现的约瑟夫环问题解决方案。该程序模拟了古代法官使用独特逻辑来决定犯人生死的过程:犯人们围成一圈,从指定位置开始,每隔固定人数就处决一人,直到剩下最后一人。程序使用字符数组记录每个人的状态,并通过循环指针进行遍历。
291

被折叠的 条评论
为什么被折叠?



