[ 백준 ] 16943 / 숫자 재배치

金弘均·2021년 9월 16일
0

Baekjoon Online Judge

목록 보기
161/228
post-thumbnail

# Appreciation

/*
 * Problem :: 16943 / 숫자 재배치
 *
 * Kind :: Math
 *
 * Insight
 * - 주어진 숫자는 최대 9자리
 *   9! = 362880
 *   + 가능한 경우가 얼마 안되니, 다 만들어서 확인해보자
 *
 * Point
 * - 만들 수 있는 수들 중 가장 큰 숫자부터 만들고 <= 내림차순 정렬
 *   차례대로 그 다음 큰 숫자를 확인하자 <= prev_permutation
 *   + 그러다가 B 이하인 수가 나오면 바로 그 숫자가 답이다!
 *
 * - A 를 각 자리수를 구해 Vector 에 구해주는게 정석같은 느낌이지만...
 *   C 를 구할 때 Vector 는 3줄 필요하지만 stoi 는 1줄이면 충분해서...
 */

# Code

//
//  BOJ
//  ver.C++
//
//  Created by GGlifer
//
//  Open Source

#include <iostream>
#include <algorithm>

using namespace std;

#define endl '\n'

// Set up : Global Variables
/* None */

// Set up : Functions Declaration
/* None */


int main()
{
    // Set up : I/O
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // Test

    // Set up : Input
    int A, B;
    cin >> A >> B;

    // Process
    string C = to_string(A); /* int to string */
    sort(C.begin(), C.end(), greater<>()); /* 내림차순 정렬 */

    int ans = -1;
    do {
        if (C.front() == '0') continue; /* 0 으로 시작하면 안 됨 */

        if (stoi(C) <= B) { /* string to int */
            ans = stoi(C);
            break;
        }
    } while (prev_permutation(C.begin(), C.end()));

    // Control : Output
    cout << ans << endl;
}

// Helper Functions
/* None */
profile
이런 미친 게임을 봤나! - 옥냥이

0개의 댓글