1 条题解
-
0
练60.6 胡萝卜与骨头
解题思路
把30位置全部放入圈,按约瑟夫过程从1开始每逢9移除,移掉的15位放胡萝卜,剩余15位放骨头。按编号排序输出剩余位置。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
初始报数1在位置1;只移除15个,不把30个都删完。
复杂度
固定30位置,时间O(1),空间O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); vector<int> a(30); iota(a.begin(), a.end(), 1); int pos = 0; for (int i = 0; i < 15; i++) { pos = (pos + 8) % a.size(); a.erase(a.begin() + pos); } for (size_t i = 0; i < a.size(); i++) { if (i) cout << " "; cout << a[i]; } cout << "\n"; return 0; }
- 1