LoginSignup
1
0

More than 3 years have passed since last update.

yukicoder No.927 Second Permutation

Posted at

問題リンク

解説

最も大きい並べ替えは降順ソートで求まる。
$2$ 番目に大きい並べ替えは最も大きい並べ替えの一個前の順列なので、prev_permutationしてやればよい。
prev_permutationができない場合やprev_permutationした後の数の最初の文字が0の時は解が無いことになる。

コード

#include <bits/stdc++.h>
using namespace std;
using lint = long long;
#define all(x) (x).begin(), (x).end()

int main(){
    string X;
    cin >> X;
    sort(all(X), greater<>());
    if(!prev_permutation(all(X))){
        cout << -1 << endl;
        return 0;
    }
    if(X[0] == '0'){
        cout << -1 << endl;
        return 0;
    }
    cout << X << endl;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0