โœ๏ธToday I Learned

๐Ÿ“… 2025-07-26

  • ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ˆซ์ž ๋ณ€ํ™˜ํ•˜๊ธฐ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ˆซ์ž ๋ณ€ํ™˜ํ•˜๊ธฐ

๋ฌธ์ œ๋งํฌ

๋ฌธ์ œ ์„ค๋ช…
์ž์—ฐ์ˆ˜ x๋ฅผ y๋กœ ๋ณ€ํ™˜ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์—ฐ์‚ฐ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.
x + n
x * 2
x * 3
์ž์—ฐ์ˆ˜ x, y, n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, x๋ฅผ y๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ตœ์†Œ ์—ฐ์‚ฐ ํšŸ์ˆ˜๋ฅผ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”. ์ด๋•Œ x๋ฅผ y๋กœ ๋งŒ๋“ค ์ˆ˜ ์—†๋‹ค๋ฉด -1์„ return ํ•ด์ฃผ์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ
1 โ‰ค x โ‰ค y โ‰ค 1,000,000
1 โ‰ค n < y

์ฒ˜์Œ ํ’€์ด(์‹œ๊ฐ„์ดˆ๊ณผ)

์žฌ๊ท€๋กœ ํ’€์—ˆ์ง€๋งŒ ์‹œ๊ฐ„์ดˆ๊ณผ ๋ฐœ์ƒ

#include <vector>
#include <algorithm>

using namespace std;

int cal(int x, const int& y, const int& n, int count)
{
    if (x > y) return -1;
    if (x == y) return count;

    vector<int> result;

    int temp = cal(x + n, y, n, count+1);
    if (temp > -1) result.push_back(temp);
    temp = cal(x * 2, y, n, count+1);
    if (temp > -1) result.push_back(temp);
    temp = cal(x * 3, y, n, count+1);
    if (temp > -1) result.push_back(temp);
    
    if (result.size() == 0) return -1;
    else return *min_element(result.begin(), result.end());
}

int solution(int x, int y, int n) {
    int answer = 0;
    answer = cal(x, y, n, 0);

    return answer;
}

์ตœ์ข… ํ’€์ด

๋ฉ”๋ชจ์ด์ œ์ด์…˜์œผ๋กœ ์ ‘๊ทผ

#include <vector>

using namespace std;

int solution(int x, int y, int n) {
    int answer = 0;
    vector<int>result(y+1, y);
    result[x] = 0;
    for(int i=x; i<=y; i++)
    {
        int temp = i+n;
        if(temp<=y)
        {
            result[temp] = result[i]+1>result[temp]?result[temp]:result[i]+1;
        }
        
        temp = i*2;
        if(temp<=y)
        {
            result[temp] = result[i]+1>result[temp]?result[temp]:result[i]+1;
        }
        
        temp = i*3;
        if(temp<=y)
        {
            result[temp] = result[i]+1>result[temp]?result[temp]:result[i]+1;
        }
    }
    answer = result[y]==y? -1: result[y];
    return answer;
}

๐Ÿ’ก ๋А๋‚€ ์  (What I Felt)

ํ•ญ์ƒ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฌธ์ œ๋‹ค. ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๊ฒŒ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€๋ฅผ ๋งŽ์ด ํ•ด์•ผ๊ฒ ๋‹ค.


์ถœ์ฒ˜ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค: ์ˆซ์ž ๋ณ€ํ™˜ํ•˜๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€