约瑟夫环问题

   //有n个人围成一个圈,编号1~n,从第1个开始报数,当报到m时该人出队,然后下一个人从1开始继续报数。
//输出所有人出队的顺序。
1
#include <stdio.h> 2 int main(int argc, char *argv[]) 3 { 4 int a[1000]={0}; 5 int i,n,m; 6 int count1;//出队人数 7 int count2;//当前人报的数字 8 scanf("%d%d",&n,&m); 9 count1=0;//还没人出队 10 count2=0;//当前报数 11 i=0;//需要检查的人的下标 12 13 while(count1<n)//还有人没有出队就继续循环 14 { 15 while(a[i]!=0)//寻找下一个还没出队的人 16 { 17 i++; 18 if(i==n) i=0; 19 } 20 count2++;//找到一个没出队的人,该人报数 21 if(count2==m)//假如第i人报数m则他出队 22 { 23 printf("%d ",i+1); 24 a[i]=1; 25 count1++; 26 count2=0; 27 } 28 i++;//下次应该检查下一个人 29 if(i==n) i=0; 30 } 31 return 0; 32 }
原文地址:https://www.cnblogs.com/huashanqingzhu/p/5017061.html