报数游戏是这样的:有n个人围成一圈,按顺序从1到n编好号。从第一个人开始报数,报到m(<n)的人退出圈子;下一个人从1开始报数,报到m的人退出圈子。如此下去,直到留下最后一个人。
本题要求编写函数,给出每个人的退出顺序编号。
函数接口定义:
void CountOff( 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;
}
/* 你的代码将被嵌在这里 */
答案:
goout为报数成功而退出的人数
step为计步器
arr中值为0的元素已经报数成功 退出 值为1还未报数成功
基本思路为 循环浏览数组中的元素,一次循环找出一个报数成功而退出的人,即在数组中数出三个值为1的元素,n次循环完成所有的报数。
先检查数组中第一个元素,如果不为0,则说明其还未报数成功退出,step+1,再检查一下计步器的数值,如果小于m,则浏览下一个元素(index+1),如果等于m,说明元素index此时报数成功,将arr【index】设置为0,退出的人数goutou+1,并将out【index】=goout,退出的人数有几个,index就是第几个退出的。如果为0,则说明此元素已经退出,step不改变,跳过他,浏览下一个元素。
void CountOff(int n, int m, int out[]) {
int arr[MAXN];
int goout = 0;
int index = 0;
for (int i = 0; i < n; i++) {
arr[i] = 1; // 1表示在圈内
}
while (goout < n) {
int step = 0;
while (step < m) {
if (arr[index] != 0) {
step = step + 1;
if(step<m)
index = (index + 1) % n;
}
else {
index = (index + 1)%n;
}
}
arr[index] = 0;
goout++;
out[index] = goout;
}
}

4万+

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



