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

[SW Expert Academy] - (D3)5215. ํ–„๋ฒ„๊ฑฐ ๋‹ค์ด์–ดํŠธ(์กฐํ•ฉ)

by ์ฃผ๋ฐœ2 2020. 6. 27.
๋ฐ˜์‘ํ˜•

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWT-lPB6dHUDFAVT&categoryId=AWT-lPB6dHUDFAVT&categoryType=CODE

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

์ฝ”๋“œ

import java.util.Scanner;

public class Solution {
	static int N;	// ์žฌ๋ฃŒ ์ˆ˜
	static int L;	// ์ œํ•œ ์นผ๋กœ๋ฆฌ
	static int ans;	// ์ตœ๋Œ€ ์ ์ˆ˜
	static int[] score;	// ์ ์ˆ˜
	static int[] cal;	// ์ œํ•œ ์นผ๋กœ๋ฆฌ
	
	/**
	 * @param count  - ์žฌ๋ฃŒ์ˆ˜ ์นด์šดํŠธ
	 * @param sum    - ์ตœ๋Œ€ ์ ์ˆ˜
	 * @param allCal - ์นผ๋กœ๋ฆฌ ํ•ฉ
	 */
	public static void dfs(int count, int sumScore, int allCal) {
		/* ๊ธฐ์ € ์‚ฌ๋ก€: ์—ฌํƒœ ๋”ํ•œ ์นผ๋กœ๋ฆฌ๋Ÿ‰์ด ์ œํ•œ ์นผ๋กœ๋ฆฌ๋ณด๋‹ค ํด๋•Œ,*/
		if(allCal > L) {
			return;
		}
		
		/* N๊ฐœ์˜ ์žฌ๋ฃŒ๊นŒ์ง€ ๋ฝ‘์•˜์„๊ฒฝ์šฐ -> ์ตœ๋Œ€ ์ ์ˆ˜ ๋น„๊ต*/
		if(count == N) {
			ans = Math.max(ans, sumScore);
			return;
		}
		
		/* ์žฌ๊ท€ํ˜ธ์ถœ(dfs): ์žฌ๋ฃŒ์ˆ˜+1, ์ ์ˆ˜, ์นผ๋กœ๋ฆฌ ํ•ฉ  */
		dfs(count+1, sumScore+score[count], allCal+cal[count]);
		
		/* ์žฌ๋ฃŒ ๋นผ๊ธฐ */
		dfs(count+1, sumScore, allCal);
	}

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int t = scan.nextInt();
		for(int tc=1; tc<=t; tc++) {
			N = scan.nextInt();	// ์žฌ๋ฃŒ ์ˆ˜
			L = scan.nextInt();	// ์ œํ•œ ์นผ๋กœ๋ฆฌ
			score = new int[N];
			cal = new int[N];
			ans = 0;
			
			for(int i=0; i<N; i++) {
				score[i] = scan.nextInt();
				cal[i] = scan.nextInt();
			}
			
			// ์žฌ๋ฃŒ๊ฐœ์ˆ˜, ์ ์ˆ˜ํ•ฉ, ์นผ๋กœ๋ฆฌ๋Ÿ‰ 0์œผ๋กœ Start
			dfs(0, 0, 0);
			
			System.out.println("#" + tc + " " + ans);
		}
		scan.close();
	}
}

ํ’€์ด

์ œํ•œ๋œ ์นผ๋กœ๋ฆฌ(L) ์—์„œ ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜๋ฅผ ์„ ํƒํ•˜๋ฉด ๋œ๋‹ค.

๋ถ€๋ถ„์ง‘ํ•ฉ์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์™€ ๋น„์Šทํ•˜๋‹ค.

๊ฐ ์›์†Œ์— ๋Œ€ํ•ด ํ•ด๋‹น ์žฌ๋ฃŒ๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ, ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ

์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋ฐ˜๋ณต์ ์œผ๋กœ ํ˜ธ์ถœํ•˜๋ฉฐ ์ตœ์ ์˜ ํ•ด๋ฅผ ์ฐพ์•„์•ผ ํ•œ๋‹ค.

์ด ๋ฌธ์ œ์—์„œ๋Š” ๋‘๊ฐ€์ง€ ์ข…๋ฃŒ์กฐ๊ฑด์ด ์žˆ๋‹ค.

 

 - ์žฌ๋ฃŒ๋ฅผ ์„ ํƒํ•˜๋ฉด์„œ ๋”ํ•ด์ง„ ์นผ๋กœ๋ฆฌ์˜ ํ•ฉ์ด ์ œํ•œ๋œ ์นผ๋กœ๋ฆฌ๋ฅผ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ

     - allCal > L

 - N๋ฒˆ์งธ ์žฌ๋ฃŒ๊นŒ์ง€ ๋ชจ๋‘ ํƒ์ƒ‰ํ•œ ๊ฒฝ์šฐ

     - count == N : ์ตœ๋Œ€ ์ ์ˆ˜๋ฅผ ๋น„๊ตํ•œ๋‹ค(maxํ•จ์ˆ˜)

 

์žฌ๊ท€ ํ˜ธ์ถœ๋ถ€๋ถ„์—์„œ๋Š”, ํƒ์ƒ‰์„ ํ•˜๋ฉฐ ์ ์ˆ˜์˜ ํ•ฉ๊ณผ ์นผ๋กœ๋ฆฌ์˜ ํ•ฉ์„ ๋”ํ•ด๊ฐ€๋Š”๋ฐ,

 - ์žฌ๋ฃŒ๋ฅผ ์„ ํƒํ•  ๊ฒฝ์šฐ: ์žฌ๋ฃŒ์™€ ์ ์ˆ˜, ์นผ๋กœ๋ฆฌ๋ฅผ ๋ชจ๋‘ ๋”ํ•ด์ค€๋‹ค.

 - ์žฌ๋ฃŒ๋ฅผ ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ: ์žฌ๋ฃŒ๋งŒ +1(๋‹ค์Œ ์žฌ๋ฃŒ๋กœ ๋„˜๊ฒจ์ฃผ๋Š”) ํ•ด์ค€๋‹ค.

 

 

์•„์ง ์ˆœ์—ด, ์กฐํ•ฉ์— ๋Œ€ํ•ด์„œ ์ •๋ฆฌ๊ฐ€ ์•ˆ๋˜์–ด์„œ ์žฌ๊ท€ ํ•จ์ˆ˜๊ฐ€ ์ต์ˆ™ํ•˜์ง€๊ฐ€ ์•Š๋‹ค...

๋น ๋ฅธ ์‹œ์ผ๋‚ด์— ์ˆœ์—ด&์กฐํ•ฉ์— ๋Œ€ํ•ด ํ•œ๋ฒˆ ์ •๋ฆฌ๋ฅผ ํ•ด์•ผ๊ฒ ๋”ฐ ,,

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€