[BOJ] 2758 ๋กœ๋˜

SSOYEONGยท2022๋…„ 4์›” 1์ผ
0

Problem Solving

๋ชฉ๋ก ๋ณด๊ธฐ
7/60
post-thumbnail

๐Ÿ”— Problem

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

๐Ÿ‘ฉโ€๐Ÿ’ป Code - Dynamic Programming

package baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

// ๋กœ๋˜

public class BJ2758 {
	
	static int t;
	static int n;
	static int m;
	static long[][] dp;
	
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		t = Integer.parseInt(br.readLine());
		
		StringTokenizer st;
		for(int i = 0; i < t; i++) {
			st = new StringTokenizer(br.readLine());
			n = Integer.parseInt(st.nextToken());
			m = Integer.parseInt(st.nextToken());
			dp = new long[n+1][m+1];
			
			solution();
			
		}
	}
	
	private static void solution() {
		
		for(int i = 1; i <= m; i++) {
			dp[1][i] = 1;
		}
		
		for(int i = 2; i <= n; i++) {
			for(int j = 2; j <= m; j++) {
				
				if(j%2 == 0) {
					dp[i][j] = dp[i][j-1] + dp[i-1][j/2];
				}
				else {
					dp[i][j] = dp[i][j-1];
				}
			}
		}
		
		long cnt = 0;
		int start = (int)Math.pow(2, n-1);		// n๋ฒˆ์งธ ๊ณ ๋ฅด๋Š” ์ˆ˜ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’
		for(int i = start; i <= m; i++) {
			cnt += dp[n][i];
		}
		
		System.out.println(cnt);
	}
	
	
}

๐Ÿ‘ฉโ€๐Ÿ’ป Code - Back Tracking

package baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

// ๋กœ๋˜
/* Back Tracking์œผ๋กœ ๊ตฌํ˜„ํ•˜๋ฉด ๋ฐฑ์ค€์—์„œ๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฐœ์ƒ
DP๋กœ ํ•ด๊ฒฐํ•˜์˜€์Œ */

public class BJ2758_2 {
	
	static int t;
	static int n;
	static int m;
	static int cnt;
	
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		t = Integer.parseInt(br.readLine());
		
		StringTokenizer st;
		for(int i = 0; i < t; i++) {
			st = new StringTokenizer(br.readLine());
			n = Integer.parseInt(st.nextToken());
			m = Integer.parseInt(st.nextToken());
			
			cnt = 0;
			backTracking(0, 0);
			
			System.out.println(cnt);
		}
	}
	
	private static void backTracking(int depth, int idx) {
		
		if(depth == n) {
			cnt++;
			return;
		}
		
		if(idx * 2 <= m) {		// isPromising() ์กฐ๊ฑด
			for(int i = idx*2; i <= m; i++) {
				if(depth == 0 && i == 0) continue;
				backTracking(depth + 1, i);
			}
		}
		else return;
		
		
	}
}

๐Ÿ“Œ Note

์•„์ด๋””์–ด

  • ์ฒ˜์Œ์— Back Tracking์œผ๋กœ ๊ตฌํ˜„ํ•ด์„œ ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฐœ์ƒํ•จ.
  • n by m matrix ๋งŒ๋“ค๊ณ  n๋ฒˆ์งธ ์ž๋ฆฌ์— m์ด ๋†“์ผ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ด์•˜๋‹ค.

ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค

  • dp[][]์™€ cnt๋ฅผ ์‹ค์ˆ˜ํ˜• double๋กœ ์„ ์–ธํ•ด์„œ ํ‹€๋ ธ๋‹ค.
  • ์ถœ๋ ฅ์ด ๋ช‡ ๊ฐœ์ธ์ง€ ๋ฌป๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ์ •์ˆ˜ํ˜• long์œผ๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ ํ•ด๊ฒฐํ•จ.
profile
รœbermensch

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