6-3 報數 (20 分)
報數游戲是這樣的:有n個人圍成一圈,按順序從1到n編好號。從第一個人開始報數,報到m(<)的人退出圈子;下一個人從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;
}
/* 你的代碼將被嵌在這里 */
輸入樣例:
11 3
輸出樣例:
4 10 1 7 5 2 11 9 3 6 8
void CountOff( int n, int m, int out[] ) { int a[MAXN],i,k=0,count=n,j=0; for(i=0;i<n;i++) //給每個位置賦初值 { a[i]= i; } for(;count!=0;i++) { if(a[i%n]!=-1)//-1表示已經退出, { k++;//報數+1 if(k==m)//報數滿足條件m { out[i%n]=n-count+1;//給對應的位置告訴他是第幾個退出的 a[i%n]=-1;//用-1賦值,在后面的報數中被屏蔽 count--;//退出一個 k=0;//重新報數 } } } }