1 条题解

  • 0
    @ 2097-12-18 7:10:39

    【例60.2】 约瑟夫问题

    解题思路

    数组维护仍在圈内的人与当前起点pos。下一淘汰下标为(pos+m-1)%人数,输出后删除该项,pos自然指向下一起点。

    正确性说明

    按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。

    易错点

    报数从1而不是0开始,所以加m-1。

    复杂度

    数组删除时间O(n²),空间O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m;
        cin >> n >> m;
        vector<int> a(n);
        iota(a.begin(), a.end(), 1);
        int pos = 0;
        bool first = true;
        while (!a.empty()) {
            pos = (pos + m - 1) % a.size();
            if (!first)
                cout << " ";
            cout << a[pos];
            first = false;
            a.erase(a.begin() + pos);
        }
        cout << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    389
    时间
    1000ms
    内存
    128MiB
    难度
    进阶
    标签
    递交数
    0
    已通过
    0
    上传者