https://www.acmicpc.net/problem/1463
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
'Algorithms > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค ์ด๋ถํ์ ๋ฌธ์ ๋ค (1072 ๊ฒ์, 1654 ๋์ ์๋ฅด๊ธฐ, 1920 ์์ฐพ๊ธฐ, 2512 ์์ฐ) (0) | 2021.11.12 |
---|---|
์ ์ฐพ๊ธฐ (๋ฐฑ์ค 1920๋ฒ, ํด์) (0) | 2021.11.04 |
์์ด ์ฌ์ดํด (๋ฐฑ์ค 10451) (0) | 2021.10.12 |
์ฐ๊ฒฐ์์์๊ฐ์ (๋ฐฑ์ค 11724) (0) | 2021.10.12 |
์ด๋ถ ๊ทธ๋ํ (๋ฐฑ์ค 1707) (0) | 2021.10.08 |