๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Problem Solving

[Java] ๋ฐฑ์ค€ 31804 - Chance!

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


ํ’€์ด

์ฒ˜์Œ์—๋Š” ๊ทธ๋ฆฌ๋”” ๋ฌธ์  ๊ฐ€? ํ–ˆ๋Š”๋ฐ ๊ทธ๊ฑด ์•„๋‹ˆ์—ˆ๊ณ  dp ๋ฌธ์ œ์˜€๋‹ค.

์ฐฌ์Šค๋ฅผ ์‚ฌ์šฉํ•œ ๊ฒฝ์šฐ์™€ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋‘˜๋กœ ๋‚˜๋ˆ ์„œ dp ๋ฐฐ์—ด์„ ์ฑ„์›Œ์ฃผ๋ฉด ๋œ๋‹ค.

 

i = ์ ์ˆ˜

dp[i][0] = ์ฐฌ์Šค๋ฅผ ์•„์ง ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์„ ๋•Œ

dp[i][1] = ์ฐฌ์Šค๋ฅผ ์ด๋ฏธ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ

 

dp[i][0]์„ ์ฑ„์šฐ๊ธฐ ์œ„ํ•ด์„œ๋Š” dp[i - 1][0], dp[i / 2][0]์˜ ๊ฐ’์„ ์‚ดํŽด๋ณด๊ณ 

dp[i][1]์„ ์ฑ„์šฐ๊ธฐ ์œ„ํ•ด์„œ๋Š” dp[i - 1][1], dp[i / 2][1], dp[i / 10][0]์˜ ๊ฐ’์„ ์‚ดํŽด๋ณธ๋‹ค.

 

์ฃผ์˜ํ•  ์ ์€ i๊ฐ€ 2์˜ ๋ฐฐ์ˆ˜์ธ์ง€๋„ ํ™•์ธํ•ด์•ผ ํ•œ๋‹ค.


์ฝ”๋“œ

๋”๋ณด๊ธฐ
import java.io.*;
import java.util.*;

public class Main {
	private static final int INF = 1000005;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int a = Integer.parseInt(st.nextToken());
		int b = Integer.parseInt(st.nextToken());
		int[][] dp = new int[b + 1][2];

		for (int i = 0; i <= b; i++) {
			dp[i][0] = INF; // chance ์•ˆ ์”€
			dp[i][1] = INF; // chance ์”€
		}

		dp[a][0] = 0;

		for (int i = a + 1; i <= b; i++) {
			if (i % 2 == 0) {
				dp[i][0] = Math.min(dp[i - 1][0] + 1, dp[i / 2][0] + 1);
				dp[i][1] = Math.min(dp[i - 1][1] + 1, dp[i / 2][1] + 1);
				if (i % 10 == 0) {
					dp[i][1] = Math.min(dp[i][1], dp[i / 10][0] + 1);
				}
			} else {
				dp[i][0] = dp[i - 1][0] + 1;
				dp[i][1] = dp[i - 1][1] + 1;
			}
		}

		System.out.println(Math.min(dp[b][0], dp[b][1]));
		br.close();
	}
}

 


ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค

๋”๋ณด๊ธฐ
// case 1:
1 12
ans: 3

// case 2:
1 1
ans: 0

// case 3:
2 30
ans: 2