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

[๋ฐฑ์ค€] 15652๋ฒˆ: N๊ณผ M (4) (dfs, ์ค‘๋ณตํฌํ•จ, ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ)

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

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

 

15652๋ฒˆ: N๊ณผ M (4)

ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ค‘๋ณต๋˜๋Š” ์ˆ˜์—ด์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์ถœ๋ ฅํ•˜๋ฉด ์•ˆ๋˜๋ฉฐ, ๊ฐ ์ˆ˜์—ด์€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. ์ˆ˜์—ด์€ ์‚ฌ์ „ ์ˆœ์œผ๋กœ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

www.acmicpc.net

์ฝ”๋“œ

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

public class Main {
	public static int arr[];
	public static int N;
	public static int M;
	public static StringBuilder sb = new StringBuilder();
	
	public static void dfs(int count) {
		if(count == M) {
			for(int i=0; i<M-1; i++) {
				if(arr[i] > arr[i+1])
					return;
			}
			
			for(int i : arr) 
				sb.append(i + " ");
			sb.append("\n");
			return;
		}
		
		for(int i=1; i<=N; i++) {
			arr[count] = i;
			dfs(count+1);
		}
		
	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String str = bf.readLine();
		StringTokenizer st = new StringTokenizer(str);
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		arr = new int[M];
		dfs(0);
		
		System.out.println(sb);
		bf.close();
	}

}

ํ’€์ด

N๊ณผ M(2) + N๊ณผ M(3) ๋‘ ๋ฌธ์ œ๋ฅผ ์„ž์–ด ๋งŒ๋“  ๋ฌธ์ œ์ด๋‹ค.

์ค‘๋ณตํ—ˆ์šฉ + ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ

์ค‘๋ณตํ—ˆ์šฉ -> ๋ฐฉ๋ฌธ์ฒดํฌ X, ๊ฐ™์€ ๊ณณ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋‹ค.

๋น„๋‚ด๋ฆผ์ฐจ์ˆœ -> arr[i] > arr[i+1] ์ด ์ฐธ์ผ๋•Œ, return; ์„ ํ†ตํ•ด ์žฌ๊ท€ํ˜ธ์ถœํ•œ dfs()๋ฉ”์†Œ๋“œ๋ฅผ ์ข…๋ฃŒํ•œ๋‹ค.

 

N๊ณผ M(1)

N๊ณผ M(2)

N๊ณผ M(3)

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€