코딩 테스트 준비/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>() 내림차순