[BOJ]1463 1๋ง๋ค๊ธฐ๐ข (java,kotlin)
โ๋ฌธ์ โ
๐Solution(java)๐
dfs๋ก ํ์ด(์๊ฐ ์ด๊ณผ)
public class S3_1463_make_one {
private static int[] res;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder builder = new StringBuilder();
int n = Integer.parseInt(br.readLine());
res = new int[n + 1];
int count = dfs(n);
builder.append(dfs(n));
System.out.println(builder);
}
static int dfs(int n) {
if (res[n] != 0) return res[n];
int[] counts = new int[4];
if (n == 3 || n == 2) return 1;
if (n % 3 == 0) {
counts[3] += dfs(n / 3) + 1;
}
if (n % 2 == 0) {
counts[2] += dfs(n / 2) + 1;
}
counts[1] += dfs(n - 1) + 1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0 && counts[i] < min) min = counts[i];
}
res[n] = min;
return min;
}
}
์ฒ์์ ๋ฌธ์ ๋ฅผ ๋ดค์ ๋ DFS๋ก ํ๋ฉด ํ๋ฆฌ๊ฒ ๋ค ์ถ์ด์ DFS๋ก ํ์๋๋ ์ ๋ ฅ๊ฐ์ด 50000์ ๋๋ง ๋๋ stackoverflow๊ฐ ๋ฐ์ํ๋ค.( ์ต๋์ ๋ ฅ๊ฐ์ 10^6 ์ด์๋คใ ใ )
DFS๋ก ํ๋ฆฌ๊ธด ํ์ด์ ์ ๊ทผ๋ฒ์ด ํ๋ ธ๋ค๊ธฐ ๋ณด๋ค๋ ๊ตฌํ๋ฐฉ์์ ๋ฐ๋ณต๋ฌธ ๊ธฐ๋ฐ DFS๋ก ๋ฐ๊พธ๋ฉด ํ๋ฆฌ์ง ์์๊น ์๊ฐ์ด ๋ค์๋๋ฐ ์๊ฐ๋ณด๋ค ์ง๊ด์ ์ด์ง ์์์ ์ด๋ ค์ ๊ณ ํ๋ฉด ํ์๋ก DP๊ตฌํ์ ๊ฐ๊น์์ง๋ค๋ ๋๋์ ๋ฐ์๋ค.
๋ค๋ฅธ ์ฌ๋๋ค์ ์ด๊ฑธ ์ด๋ป๊ฒ ๊ตฌํํ๋ ์ถ์ด ์ฐพ์๋ณด๋ ์ด ๋ฌธ์ ๊ฐ ๋ํ์ ์ธ DP๋ฌธ์ ๋ผ๊ณ ํ๋ค..ใ
๊ดํ ์ด๊ฒ ๋๋ฌธ์ ์๊ฐ ์ก์๋จน๊ณ ํ์ต์์ง๋ ๋จ์ด์ก์๋๋ฐ ๊ทธ๋ฅ ์ข ์ผ์ฐ ํ์ธํ ๊ฑธ ๊ทธ๋ฌ๋ค๋ ์๊ฐ์ด ๋ ๋ค.๐
DP๋ก ํ์ด
import java.io.*;
public class S3_1463_make_one {
private static int[] res;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder builder = new StringBuilder();
int n = Integer.parseInt(br.readLine());
res = new int[n + 1];
int count = dp(n);
builder.append(count);
System.out.println(builder);
}
static int dp(int n){
int[] res=new int[n+1];
if(n>2) res[3]=1;
if(n>1)res[2]=1;
for(int i=4;i<=n;i++){
int min=Integer.MAX_VALUE;
if(i%2==0) min=Math.min(res[i/2],min);
if(i%3==0) min=Math.min(res[i/3],min);
min=Math.min(res[i-1],min);
res[i]=min+1;
}
return res[n];
}
}
DP๋ก ํธ๋๊น ์์ ๋นจ๋ฆฌ ํ๋ ธ๋ค..
๐ Language Change(kotlin)๐
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Integer.min
fun main(){
val br=BufferedReader(InputStreamReader(System.`in`))
val builder=StringBuilder()
val n=br.readLine().toInt()
builder.append(dp(n))
println(builder)
}
fun dp(n:Int):Int{
val res=Array(n + 1){0}
if(n>1) res[2]=1
if(n>2) res[3]=1
for(i in 4..n){
var min=Int.MAX_VALUE
if(i%3==0) min=min(res[i/3],min)
if(i%2==0) min=min(res[i/2],min)
min=min(res[i-1],min)
res[i]=min+1
}
return res[n]
}
๐Advanced๐
- ๋๋ 4~n๊น์ง ๋ฐ๋ณต์ ๋๋ ธ๋๋ฐ res[1]์ ์ ์ํด์ 2~n๊น์ง ๋ฐ๋ณต์ ๋๋ฆฌ๋ฉฐ ์ ํ์์ผ๋ก res[2],res[3]์ ์ ์ํ๋ ์ฝ๋๋ ์์๋ค.
-
๋ฐ๋ณต๋ฌธ ๋ด๋ถ ์ฝ๋๋ ์๋์ ๊ฐ์ด ๋ณํํด์ผ ๋ ํจ์จ์ ์ผ ๊ฒ ๊ฐ๋ค.
var min=res[i-1] if(i%3==0) min=min(res[i/3],min) if(i%2==0) min=min(res[i/2],min)
๋๊ธ๋จ๊ธฐ๊ธฐ