λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Algorithm πŸ§‘πŸ»‍πŸ’»/λ°±μ€€(BOJ)

[λ°±μ€€,c++] 1174번 - μ€„μ–΄λ“œλŠ” 수

by μ•ˆμ£Όν˜• 2022. 8. 21.

문제

 

1174번: μ€„μ–΄λ“œλŠ” 수

음이 μ•„λ‹Œ μ •μˆ˜λ₯Ό μ‹­μ§„λ²•μœΌλ‘œ ν‘œκΈ°ν–ˆμ„ λ•Œ, μ™Όμͺ½μ—μ„œλΆ€ν„° μžλ¦¬μˆ˜κ°€ κ°μ†Œν•  λ•Œ, κ·Έ 수λ₯Ό μ€„μ–΄λ“œλŠ” 수라고 ν•œλ‹€. 예λ₯Ό λ“€μ–΄, 321와 950은 μ€„μ–΄λ“œλŠ” 수이고, 322와 958은 μ•„λ‹ˆλ‹€. N번째둜 μž‘μ€ μ€„μ–΄λ“œλŠ”

www.acmicpc.net

 

μ½”λ“œ

#include <iostream>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;

int N;
string num = "0123456789";
vector<ll> asc;

void backtracking(int idx, string temp){
    
    if(!temp.empty()){
        string _temp = temp;
        reverse(_temp.begin(),_temp.end());
        asc.push_back(stoll(_temp));
    }
    
    for(int i=idx+1; i<10; i++){
        temp += num[i];
        backtracking(i, temp);
        temp.pop_back();
    }
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    cin>>N;
    
    for(int i=0; i<10; i++){
        string temp = "";
        backtracking(i,temp+=num[i]);
    }
    
    sort(asc.begin(), asc.end());
    
    if(N>asc.size()) cout<<-1;
    else cout<<asc[N-1];
    
}

 

풀이

μ „ν˜•μ μΈ λ°±νŠΈλž™ν‚Ή λ¬Έμ œμ˜€μŠ΅λ‹ˆλ‹€.

μ€„μ–΄λ“œλŠ” λͺ¨λ“  수λ₯Ό 배열에 μ €μž₯해놓고 λ§ˆμ§€λ§‰μ— ν•΄λ‹Ή μˆœλ²ˆμ— ν•΄λ‹Ήν•˜λŠ” 수λ₯Ό 좜λ ₯ν•˜λŠ” λ°©μ‹μœΌλ‘œ ν•΄κ²°ν–ˆμŠ΅λ‹ˆλ‹€. 

μ€„μ–΄λ“œλŠ” λ°©μ‹μœΌλ‘œ ν•˜μžλ‹ˆ 보기가 λΆˆνŽΈν•΄ μ¦κ°€ν•˜λŠ” μˆ˜μ—΄λ‘œ λ§Œλ“€μ–΄κ°€λ©΄μ„œ 배열에 넣을 λ•ŒλŠ” reverse μ‹œμΌœμ„œ μ΅œμ’…μ μœΌλ‘œ μ€„μ–΄λ“œλŠ” μˆ˜λ“€μ„ λ„£μ—ˆμŠ΅λ‹ˆλ‹€.

λŒ“κΈ€