Algorithms/Algorithms

1๋กœ๋งŒ๋“ค๊ธฐ (๋ฐฑ์ค€1463)

ํƒฑ์ ค 2021. 10. 13. 15:00

https://www.acmicpc.net/problem/1463

 

1463๋ฒˆ: 1๋กœ ๋งŒ๋“ค๊ธฐ

์ฒซ์งธ ์ค„์— 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 106๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net


Dnamic Programming(๋™์ ๊ณ„ํš๋ฒ•)์€ ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ํ†ตํ•ด ์ค‘๋ณต๊ณ„์‚ฐ๊ฐ’์„ ์ €์žฅํ•ด ํšจ์œจ์„ ๋†’์—ฌ์ค€๋‹ค.

1) Python ์ด์šฉ

# DP --> ๋ฉ”๋ชจ์ด์ œ์ด์…˜: ์ค‘๋ณต๊ณ„์‚ฐ๊ฐ’์„ ์ค„์—ฌ ํšจ์œจ ๋†’์—ฌ์คŒ

n = int(input())

d = [0] * (n + 1) 
# d์— ๊ณ„์‚ฐ๊ฐ’ ์ €์žฅ
# d[0] = 0, d[1] = 0

for i in range(2, n + 1):
    d[i] = d[i - 1] + 1
    if i % 3 == 0:
        d[i] = min(d[i], d[i // 3] + 1)
    if i % 2 == 0:
        d[i] = min(d[i], d[i // 2] + 1)

print(d[n])

2) C ์ด์šฉ (C ๋„ˆ๋ฌด ์˜ค๋žœ๋งŒ์ด๋ผ ์•ˆ๊นŒ๋จน์„๋ ค๊ตฌ,,,)

#include <stdio.h>
#include <stdlib.h>
#define min(x, y) ((x) < (y) ? (x) : (y))

int main()
{
    int n;
    scanf("%d", &n);
    int d[n + 1];
    d[0] = 0;
    d[1] = 0;
    for(int i = 2; i <= n + 1; i++)
    {
        d[i] = d[i - 1] + 1;
        if(i % 3 == 0) d[i] = min(d[i], d[(int)(i / 3)] + 1);
        if(i % 2 == 0) d[i] = min(d[i], d[(int)(i / 2)] + 1);
    }
    printf("%d", d[n]);
    
}

3) C++ ์ด์šฉ (C++๋„ ํ•œ๋ฒˆ ๋ฐฐ์›Œ๋ณด๊ธฐ,,,)

#include <iostream>
#include <algorithm>
using namespace std;

int d[10000001];

int main(){
    int n;
    
    cin >> n;

    for(int i = 2; i <= n; i++){
        d[i] = d[i - 1] + 1;
        if(i % 2 == 0) d[i] = min(d[i], d[i / 2] + 1);
        if(i % 3 == 0) d[i] = min(d[i], d[i / 3] + 1);
    }

    cout << d[n] << endl;

    return 0;
}
728x90