๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 2992_ํฌ๋ฉด์„œ ์ž‘์€ ์ˆ˜

๋ฟŒ์•ผ._. 2023. 10. 5. 18:25

Silver III

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

< ํฌ๋ฉด์„œ ์ž‘์€ ์ˆ˜ >

 

๋ฌธ์ œ ํ’€์ด 

 

X๋ณด๋‹ค ํฐ ์ˆ˜ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด X๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅํ•˜์—ฌ ์ •๋ ฌํ•œ๋‹ค.

์ •๋ ฌํ•œ ๋ฐฐ์—ด์„ ์กฐํ•ฉ๋ก ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ•œ๋‹ค.

 

 my solution (Java)

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

public class _2992_ { // ํฌ๋ฉด์„œ ์ž‘์€ ์ˆ˜
	static int temp[], result[];
	static boolean visited[], flag;
	static String str, answer;

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

		str = bf.readLine();

		temp = new int[str.length()];
		result = new int[str.length()];
		visited = new boolean[str.length()];
		flag = false;

		for (int i = 0; i < str.length(); i++) {
			temp[i] = str.charAt(i) - '0';
		}

		Arrays.sort(temp);

		search(0);

		if (!flag)
			System.out.println(0);
	}

	private static void search(int idx) {
		if (idx == result.length) {
			answer="";
			for (int i = 0; i < result.length; i++) {
				answer += Integer.toString(result[i]);
			}

			if (!flag && Integer.parseInt(answer) > Integer.parseInt(str)) {
				flag = true;
				System.out.println(answer);
			}

			return;
		}

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

 

Main

๋ณ€์ˆ˜)
str : ์ •์ˆ˜ X
temp : ์ •์ˆ˜ X๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ์ˆซ์ž
result : ๊ฒฐ๊ณผ ์ €์žฅ ๋ฐฐ์—ด
visited : ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
flag : ์ •๋‹ต ์—ฌ๋ถ€

 

- ์ •์ˆ˜ X(str) ์ž…๋ ฅ

- ์ •์ˆ˜ X๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ์ˆซ์ž๋ฅผ ๋ฐฐ์—ด temp์— ์ €์žฅ ํ›„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

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

- ์ •์ˆ˜ X๋ณด๋‹ค ํฐ ์ˆ˜ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์—†๋‹ค๋ฉด 0 ์ถœ๋ ฅ

 

Search

- X์™€ ๊ตฌ์„ฑ์ด ๊ฐ™์€ ์ˆ˜๋ฅผ ๊ตฌํ–ˆ๋‹ค๋ฉด ์•„์ง ์ •๋‹ต์„ ์ฐพ์ง€ ๋ชปํ–ˆ๊ณ  ๊ทธ ์ˆ˜๊ฐ€ ์ •์ˆ˜ X๋ณด๋‹ค ํฐ ์ˆ˜๋ผ๋ฉด ๋‹ต์ด๋ฏ€๋กœ ์ •๋‹ต ์ถœ๋ ฅ

- temp ๋ฐฐ์—ด์„ ์ˆœํ™˜ํ•˜๋ฉฐ ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ˆ˜๋ผ๋ฉด ๋ฐฉ๋ฌธ ํ‘œ์‹œ ๋ฐ result ๋ฐฐ์—ด์— ์ €์žฅ ํ›„ ๋‹ค์‹œ search ํ•จ์ˆ˜ ํ˜ธ์ถœ. ํ•จ์ˆ˜ ํ˜ธ์ถœ ํ›„ ๋‹ค์Œ ์กฐํ•ฉ์„ ์œ„ํ•ด ๋ฐฉ๋ฌธ ํ‘œ์‹œ๋ฅผ ํ•ด์ œ (๋งŒ์•ฝ flag๊ฐ€ true๋ผ๋ฉด ์ด๋ฏธ ๋‹ต์„ ๊ตฌํ•ด์„œ ๋‹ค์Œ ์กฐํ•ฉ์„ ๊ตฌํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ return)