์‹ค๋ฒ„1 : ๋™์  ๊ณ„ํš๋ฒ• ๋ฌธ์ œ์ด๋‹ค.

์ƒ๊ฐ

์ „ํ˜•์ ์ธ dp ๋ฌธ์ œ์ด๋‹ค. ๋‹ค๋งŒ ์ด ๋ฌธ์ œ๋Š”, ๊ฒฝ๋กœ๋ฅผ ์ถ”์ ํ•ด์•ผ ํ•œ๋‹ค๋Š” ์ ์—์„œ ์กฐ๊ธˆ ๋‹ค๋ฅด๋‹ค. ๊ฒฝ๋กœ๋ฅผ ์ถ”์ ํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” dp๋ฅผ ๋ฏธ๋ฆฌ ๊ตฌํ•ด๋†“๊ณ , ์ด๊ฒƒ์„ ์—ญ์œผ๋กœ ์ถ”์ ํ•˜์—ฌ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๊ฐ€์žฅ ๊ฐ„๋‹จํ•˜๋‹ค.

Code

#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
#include<cmath>
#include<functional>
using namespace std;
int N;
int dp[1000001];
vector<int> trace;
 
void tracing(int num){
    trace.push_back(num);
    if (num == 1) return;
    int before = num-1;
    if (num%3 == 0) {
        if (dp[before] > dp[num/3]) before = num/3;
    }
    if(num%2 == 0) {
        if (dp[before] > dp[num/2]) before = num/2;
    }
    tracing(before);
}
 
int main(){
    cin >> N;
    dp[0] = 987654321;
    for (int i = 2; i <= N; i++) {
        dp[i] = dp[i-1] + 1;
        if (i%3 == 0) {
            dp[i] = min(dp[i], dp[i/3]+1);
        }
        if (i%2 == 0){
            dp[i] = min(dp[i], dp[i/2]+1);
        }
    }
    tracing(N);
 
    cout << dp[N] << endl;
    for (int i = 0; i < trace.size(); i++) {
        cout << trace[i] << ' ';
    }
 
    return 0;
}

Reference