๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 5568_์นด๋“œ ๋†“๊ธฐ

๋ฟŒ์•ผ._. 2023. 10. 11. 11:31

Silver IV

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/5568)

< ์นด๋“œ ๋†“๊ธฐ >

 

๋ฌธ์ œ ํ’€์ด 

 

์กฐํ•ฉ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ •์ˆ˜๋ฅผ ๋งŒ๋“  ํ›„ ์ค‘๋ณต์„ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•ด set์— ๋„ฃ์€ ํ›„ set์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class _5568_ { // ์นด๋“œ ๋†“๊ธฐ
	static String arr[], result[];
	static boolean visited[];
	static Set<Integer> set;

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(bf.readLine());
		int k = Integer.parseInt(bf.readLine());

		arr = new String[n];
		result = new String[k];
		visited = new boolean[n];
		set = new HashSet<>();

		for (int i = 0; i < n; i++) {
			arr[i] = bf.readLine();
		}

		search(0, k);

		System.out.println(set.size());
	}

	private static void search(int idx, int k) {
		if (idx == k) {
			String str = "";
			for (int i = 0; i < k; i++) {
				str += result[i];
			}
			set.add(Integer.parseInt(str));

			return;
		}

		for (int i = 0; i < arr.length; i++) {
			if (!visited[i]) {
				visited[i] = true;
				result[idx] = arr[i];
				search(idx + 1, k);
				visited[i] = false;
			}
		}
	}
}

 

Main

๋ณ€์ˆ˜)
n : ์นด๋“œ ์ˆ˜
k : ์„ ํƒํ•˜๋Š” ์นด๋“œ ์ˆ˜
arr : ์นด๋“œ ์ €์žฅ ๋ฐฐ์—ด
result : ์„ ํƒํ•œ ์นด๋“œ ์ €์žฅ ๋ฐฐ์—ด
visited : ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
set : ์กฐํ•ฉํ•œ ์ •์ˆ˜ ์ €์žฅ

 

- ์นด๋“œ ์ˆ˜(n), ์„ ํƒํ•˜๋Š” ์นด๋“œ ์ˆ˜(k) ์ž…๋ ฅ

- ์นด๋“œ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋ฐฐ์—ด์— ์ €์žฅ(arr)

- search ํ•จ์ˆ˜ ํ˜ธ์ถœ

- ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜(set์˜ ํฌ๊ธฐ) ์ถœ๋ ฅ

 

Search

- k๊ฐœ๋งŒํผ ์นด๋“œ๋ฅผ ์„ ํƒํ–ˆ๋‹ค๋ฉด set์— ์ถ”๊ฐ€

- ์นด๋“œ ์ˆ˜(n)๋งŒํผ ๋ฐ˜๋ณต

: ์•„์ง ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์นด๋“œ๋ผ๋ฉด ์‚ฌ์šฉ ํ›„ ๋‹ค์Œ ์นด๋“œ๋ฅผ ์„ ํƒํ•˜๊ธฐ ์œ„ํ•ด search ํ•จ์ˆ˜ ํ˜ธ์ถœ

: search ํ•จ์ˆ˜ ํ˜ธ์ถœ ํ›„ ๋‹ค์Œ ์กฐํ•ฉ์„ ์œ„ํ•ด ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ์œผ๋กœ ์ €์žฅ