백준 온라인 저지

백준 10972: 다음 순열

dev_doyle 2018. 7. 17. 15:59

STL은 강력하다. 벡터에서 다음 순열과 이전수열을 구하는 알고리즘을 내장하고 있다.

사용법은 next_permutation 함수에 이터레이터의 시작과 끝을 넣어주면 된다. 다음 순열을 구했으면 true 마지막순열이었다면 false를 반환해 while문에 응용할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> perm;
int main()
{
    bool last = false;
    int input = 0;
    cin >> input;
    for (int i = 0; i < input; ++i)
    {
        int n_input;
        cin >> n_input;
        perm.push_back(n_input);
    }
    last = next_permutation(perm.begin(), perm.end());
    if (!last)
        cout << -1 << endl;
    else
    {
        for (auto itr = perm.begin(); itr != perm.end(); ++itr)
            cout << *itr << " ";
    }
    
    cout << endl;
    return 0;
}
cs