報數游戲是這樣的:有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 ne[1000]; for(int i = 0;i < n;i ++) { ne[i] = (i + 1) % n; } int c = 0,la = n - 1,p = 0; int flag = 0; while(flag < n) { if(++ c == m) { c = 0; out[p] = ++ flag; ne[la] = ne[p]; p = la; } la = p; p = ne[p]; } }