报数游戏是这样的:有n个人围成一圈,按顺序从1到n编好号。从第一个人开始报数,报到m(<n)的人退出圈子;下一个人从1开始报数,报到m的人退出圈子。如此下去,直到留下最后一个人。
本题要求编写函数,给出每个人的退出顺序编号。
函数接口定义:
voidCountOff( int n, int m, int out[] );
其中n是初始人数;m是游戏规定的退出位次(保证为小于n的正整数)。函数CountOff将每个人的退出顺序编号存在数组out[]中。因为C语言数组下标是从0开始的,所以第i个位置上的人是第out[i-1]个退出的。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 20
void CountOff( int n, int m, int out[] );
int main()
{
int out[MAXN], n, m;
int i;
scanf("%d %d", &n, &m);
CountOff( n, m, out );
for ( i = 0; i < n; i++ )
printf("%d ", out[i]);
printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
11 3
输出样例:
4 10 1 7 5 2 11 9 3 6 8
AC代码:
/*
* 报数游戏:给出每个人的退出顺序编号
*/
void CountOff(int n, int m, int out[]) {
// C 语言 C99 及以上标准支持 VLA,即使用变量定义数组大小
int people[n];
int i;
for (i = 0; i < n; i++) {
people[i] = i + 1;
}
int index = 0;
int count = 0;
// 报数 n 次,每次将出队的元素值修改为 -1
int dequeue;
for (dequeue = 1; dequeue <= n; dequeue++) {
// 一直报数,直到有人出队
while (1) {
// 循环报数
index = index == n ? 0 : index;
// 当前编号已出队,下一位
if (people[index] == -1) {
index++;
continue;
}
// 报数
count++;
// 如果当前报数 count 为 m 则出队
if (count == m) {
// 出队
people[index] = -1;
// 记录当前编号的出队顺序
out[index] = dequeue;
// 重新计数
count = 0;
// 下一位
index++;
break;
}
index++;
}
}
}
来源:https://blog.csdn.net/weixin_51008866/article/details/117275714