【题目】有n(n >1)个人围成一个圈,依次给每个人一个自然数编号(1~n自加),设定一个数字m(m <= n),手绢从1开始丢,丢到m,则m退出,然后从m+1处重新数1开始,直到最后一个人退出,问n个人依次退出的编号顺序是怎样的?
【算法】
void shift_loop(int *a,int n,int m)//move the number of m to end of a array. eg(m = 3):12345---->45123
{
int shift_count = 0;
int *temp_ptr = NULL,temp;
for(;shift_count < m;shift_count++)
{
temp_ptr = a;
for(;temp_ptr < a + n -1; temp_ptr++)//Reverse order
{
temp = *temp_ptr;
*temp_ptr = *(temp_ptr+1);
*(temp_ptr + 1) = temp;
}
}
}
void CountOff( int n, int m, int out[] )//Numbering 1~n,m is mark,if someone is m then out then from next of m to begin until last one.out[] will be stored number from 1~n
{
int index;
int count = 0;
int a[n];
for(index = 0;index < n; index++)
{
a[index] = index + 1;//store numbering
}
while(count < n)
{
shift_loop(&a[count],n - count,m - 1);//m-1 is order to make mth element to quit.
out[count] = a[count];
count++;
}
}
void CountOff_input(void)
{
int m, n;
puts("Enter n and m:");
if(scanf("%d %d",&n,&m) != EOF)
{
int out[n];
fflush(stdin);//clear input buffer,due to '\n' still in input buffer,because scanf will not get '\n' from input buffer.
CountOff(n,m,out);
for(int i = 0;i < n; i++)
{
printf("%d ",out[i]);
}
printf("\n");
}
}
void main(void)
{
CountOff_input();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)