实验8-1-8 报数(20 分)

实验8-1-8 报数(20 分)

报数游戏是这样的:有n个人围成一圈,按顺序从1到n编好号。从第一个人开始报数,报到m(<n)的人退出圈子;下一个人从1开始报数,报到m的人退出圈子。如此下去,直到留下最后一个人。

本题要求编写函数,给出每个人的退出顺序编号。

函数接口定义:

1
void CountOff( int n, int m, int out[] );

其中n是初始人数;m是游戏规定的退出位次(保证为小于n的正整数)。函数CountOff将每个人的退出顺序编号存在数组out[]中。因为C语言数组下标是从0开始的,所以第i个位置上的人是第out[i-1]个退出的。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
}

/* 你的代码将被嵌在这里 */

输入样例:

1
11 3

输出样例:

1
4 10 1 7 5 2 11 9 3 6 8

`

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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;
}
void CountOff(int n, int m, int out[])
{
int i, j, count, length, circle[MAXN], temp[MAXN];
for (i = 0, length = 0; i < n; i++)
{
circle[i] = i+1;
length++;
}

count = 0;
j = 0;
while (length > 0)
{
for (i = 0; i < n; i++)
{
if (circle[i] != 0)
count++;
else
continue;
if (count%m == 0)
{
temp[j] = circle[i];
j++;
circle[i] = 0;
length--;
}
}
}

for (i = 0; i < n; i++)
{
j = temp[i];
out[j-1] = i + 1;
}
}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×