코딩테스트/Baekjoon

[백준 #10972] 다음 순열 (C++)

동띵 2021. 9. 8. 15:05

https://www.acmicpc.net/problem/10972

 

10972번: 다음 순열

첫째 줄에 입력으로 주어진 순열의 다음에 오는 순열을 출력한다. 만약, 사전순으로 마지막에 오는 순열인 경우에는 -1을 출력한다.

www.acmicpc.net

 

algorithm 헤더 파일에 정의된

next_permutation()을 사용하여 문제를 풀었다.

 

next_permutation()은 다음 순열이 없다면 false를 반환하고

현재 순열의 다음 순열이 있다면 이를 구하고 true를 반환한다.

 

따라서 if 문을 사용해 다음 순열이 있으면 그것을 출력하고,

입력한 순열이 사전 순으로 마지막에 오는 순열이면 -1을 출력했다.

 

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	int n, num;
	cin >> n;
	vector<int> v(n);

	for (int i = 0; i < n; i++) {
		cin >> v[i];
	}

	if (next_permutation(v.begin(), v.end()))
	{
		for (int i = 0; i < n; i++) {
			cout << v[i] << " ";
		}
	}
	else {
		cout << -1;
	}

	return 0;
}