Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 공부

정렬 (feat. 순열) 본문

코딩 테스트 준비/c++

정렬 (feat. 순열)

방구석개발입문 2022. 11. 15. 00:46

지금까지 정렬을 for문으로 구현을 해왔지만,,,

<algorithm>헤더를 사용해

 

sort(begin, end)

를 이용해 오름차순 정렬 가능!

int arr[10] ={ 1, 3, 5, 7, 9, 2,4 ,6,8, 0};

sort(arr, arr+10, (desc => 내림차순 가능));

 

 

 

순열 : 서로 다른 n개의 원소에서 r개를 중복없이 순서에 상관 있게 선택, 나열하는 것

next_permutation,
prev_permutation (이전순열)

        string num;
        cin >> N;
        num = stoi(N);
        s = "impossible";

        while (next_permutation(N.begin(), N.end())) // 순열 출력
        {
            if (stoi(N) % num == 0)
            {
                s = "possible";
                break;
            }

1234가 있으면

 

1243

1324

1342

...

4321 이런식이 순열

 

 

 

 

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    int a,b;
    cin >>a;
    
    for(int i=0; i<a; i++)
    {
        cin >> b;
        string str = to_string(b);
        string value = "impossible";
        
        while (next_permutation(str.begin(), str.end()))
        {
            int num = stoi(str);
            if(num % b == 0)
            {
                value = "possible";
                break;
            }
        }
        cout << "#" << i << " " << value << endl;
    }
    
}

 

 

 

 

string 정렬

sort(str.begin(), str.end(), 옵션);

옵션으로 greater<int>() 내림차순