๋ฌธ์ (์ถ์ฒ: 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)
'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 25192_์ธ์ฌ์ฑ ๋ฐ์ ๊ณฐ๊ณฐ์ด (0) | 2023.10.09 |
---|---|
[Baekjoon] 16943_์ซ์ ์ฌ๋ฐฐ์น (0) | 2023.10.06 |
[Baekjoon] 19941_ํ๋ฒ๊ฑฐ ๋ถ๋ฐฐ (0) | 2023.10.04 |
[Baekjoon] 10709_๊ธฐ์์บ์คํฐ (1) | 2023.10.03 |
[Baekjoon] 6146_์ ์๋ฅผ ๋ง๋๋ฌ (1) | 2023.10.02 |