srupのメモ帳

競プロで解いた問題や勉強したことを記録していくメモ帳

next_permutation の逆 辞書順の大きい順番

comp を指定する

https://cpprefjp.github.io/reference/algorithm/next_permutation.html
上のサイトを見ると, 第三引数に比較関数を取れるので, 比較関数を作れば辞書順の逆でやることも可能.

プログラムは以下の通りになる.

#include <bits/stdc++.h>
using namespace std;

bool comp(int i, int j) {
    return i > j;
}

int main(void) {
    vector<int> v{1, 2, 3};
    sort(v.begin(), v.end(), comp);
    
    do {
        for(auto u : v) cout << u << " ";
        cout << endl;
    }while( next_permutation(v.begin(), v.end(), comp) );
   
    return 0;
}

出力は以下の通りになる.

3 2 1 
3 1 2 
2 3 1 
2 1 3 
1 3 2 
1 2 3 

prev_permutation がありました.

#include <bits/stdc++.h>
using namespace std;

int main(void) {
    vector<int> v{1, 2, 3};
    sort(v.begin(), v.end());
    reverse(v.begin(), v.end());
                
    do {
        for(auto u : v) cout << u << " ";
        cout << endl;
    }while( prev_permutation(v.begin(), v.end()) );
   
    return 0;
}

上のプルグラムの出力はcompのと一致します.