1 条题解

  • 0
    @ 2058-5-8 19:20:57

    【例57.2】 上一个排列

    解题思路

    调用prev_permutation求当前排列字典序前驱,返回false说明已经最小,输出ERROR;否则逐项输出。

    正确性说明

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

    易错点

    函数返回false会把数组改成最大排列,此时仍须输出ERROR。

    复杂度

    时间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;
        cin >> n;
        vector<int> a(n);
        for (int &x : a)
            cin >> x;
        if (!prev_permutation(a.begin(), a.end()))
            cout << "ERROR\n";
        else {
            for (int i = 0; i < n; i++) {
                if (i)
                    cout << " ";
                cout << a[i];
            }
            cout << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    378
    时间
    1000ms
    内存
    64MiB
    难度
    普及−
    标签
    递交数
    0
    已通过
    0
    上传者