約瑟夫環問題:N 人圍圈,每隔 M-1 人淘汰第 M 個,求最後倖存者位置。MFC 界面實現需包含參數輸入、動畫演示、結果顯示。
CSDN 博客提供完整 MFC 對話框專案源碼:
MFC 編寫約瑟夫生死遊戲 (含界面、動畫、源碼下載)
std::list 或循環鏈表存儲人員編號,erase 實現 O(1) 淘汰。SetTimer 觸發 OnTimer,每步高亮當前計數位置,KillTimer 結束。使用 CDC 繪製圓環分佈。CListBox::SetCurSel 高亮列表項。int josephus(int n, int m) {
list people;
for (int i = 1; i <= n; ++i) people.push_back(i);
auto it = people.begin();
while (people.size() > 1) {
for (int k = 1; k < m; ++k) {
++it; if (it == people.end()) it = people.begin();
}
// 淘汰 it
it = people.erase(it); // erase 返回下一個迭代器
if (it == people.end()) it = people.begin();
}
return people.front();
}
參考推薦源碼可快速獲得可運行的 MFC 完整專案,並可在此基礎上擴展教學/演示功能。