Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
29 | 30 |
Tags
- c++
- 스레드전용저장소
- 정처기 실기 벼락치기
- 선형대수학
- 구문트리
- 컴파일러
- 재배치
- Rust
- 정보처리기사 실기 벼락치기
- 대상파일
- CS정리
- 코드포스
- vector
- rust 스터디
- 정처기 실기 공부법
- linear algebra
- 컴퓨터밑바닥의비밀
- 행렬
- 백준
- column space
- 알고리즘
- 벡터
- unity
- matrix
- 정보처리기사 2025 1회 실기 벼락치기
- 링커
- 다이나믹 프로그래밍
- 다익스트라
- eigenvalue
- 정처기 공부법
Archives
- Today
- Total
개발_기록용
[C++] next_permutation 알고리즘 본문
728x90
알고리즘 문제를 풀다보면 순열과 조합을 구해야 하는 경우가 많다.
가령 다음과 같은 문제가 있다고 치자.
3, 4, 6으로 이루어진 수들 중 364보다 더 큰 수들 가운데 제일 작은 수를 구하시오
그럼 int arr[3] = {3, 4, 6}의 원소들을 순열로 구하면
{3, 4, 6}
{3, 6, 4}
{4, 3, 6}
{4, 6, 3}
{6, 3, 4}
{6, 4, 3}
이렇게 총 6가지가 존재해 {4, 3, 6}을 골라 436을 반환하면 된다.
next_permutation 알고리즘
https://en.cppreference.com/w/cpp/algorithm/next_permutation
std::next_permutation - cppreference.com
template< class BidirIt > bool next_permutation( BidirIt first, BidirIt last ); (1) (constexpr since C++20) template< class BidirIt, class Compare > bool next_permutation( BidirIt first, BidirIt last, Compare comp ); (2) (constexpr since C++20) Permutes th
en.cppreference.com
C++의 <algorithm> 헤더에는 순열을 구하는 next_permutation 함수가 있다.
template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last);
template<class BidirIt, class Compare >
bool next_permutation(BidirIt first, BidirIt last, Compare comp);
이 함수는 내부적으로 사전순으로 다음 순열을 생성한다.
그러면 위의 문제를 아래와 같이 풀 수 있다.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
// 다음 순열을 찾는 함수
string getNextPermutation(string number) {
// C++의 next_permutation을 사용하여 다음 순열을 찾음
if (next_permutation(number.begin(), number.end())) {
return number;
} else {
return ""; // 다음 순열이 없는 경우 빈 문자열 반환
}
}
int main() {
int N;
cin >> N;
// 숫자를 문자열로 변환
string number = to_string(N);
// 다음 순열을 찾음
string nextNumber = getNextPermutation(to_string(N));
cout << nextNumber << endl;
return 0;
}
- 단순히 모든 순열의 경우의 수를 구하기 위해 do-while 문이랑 함께 쓰이는 경우도 많이 보인다.
- 이 함수를 아느냐 모르냐에 따라 속도차이가 굉장히 크다.
- 입력이 100만이어도 1초안에 반환하니 꼭 알아두자!
반응형
'알고리즘' 카테고리의 다른 글
[C++ 에라토스테네스의 체] 소수 판별법 (1) | 2024.07.10 |
---|---|
[C++] 유클리드 호제법 - 최대공약수(GCD)와 최소공배수(LCM) (0) | 2024.07.10 |
[백준 11055번] 가장 큰 증가하는 부분 수열, C++, 테스트 케이스 (5) | 2024.06.17 |
[CodeForce 327A] Fliping Game C++ 풀이 - Maximum SubArray로 풀기 (0) | 2024.04.08 |
[Codeforce 1003C] C. Intense Heat (0) | 2024.03.15 |
Comments