【OJ】約瑟夫環問題
阿新 • • 發佈:2018-11-25
#include<stdio.h> class Person{ public: int name; bool flag; }; int main() { int m = 0; // 一共m個人 int n = 0; // 從1開始報數 報到n的那個人出列 scanf("%d%d",&m,&n); n = n-1; // 等效報的那個數 等效為從0開始報數 報到n-1的那個人出列 Person *person = new Person[m]; // 初始化 for(int i=0;i<m;i++){ person[i].flag = false; //剛開始都沒有出列 person[i].name = i + 1; // 每個人的“姓名” 這裡用數字來表示 } int pt = 0; // “等效指標” int currentPerson = m; // 記錄當前序列的人數 for(int i=0;i<m;i++){ // 迴圈 “總人數”次 int offset = n%currentPerson; // pt應該偏移這麼多 int count = 0; // 計數器 while(count!=offset||person[pt].flag==true){ // 關鍵程式碼 條件的判斷 if(person[pt].flag==true){ pt = (pt+1)%m; // %m 的目的是為了保證pt這個"等效指標"不越過陣列的邊界 continue; } pt = (pt+1)%m; count++; } printf("%d\n",person[pt].name); currentPerson--; // 當前序列總人數減一 person[pt].flag = true; // 修改那個出列的人的標記 } delete[] person;// 釋放動態陣列 return 0; }