๋ฌธ์
ํ์ด
์ด ๋ฌธ์ ๋ ๋ฐฑํธ๋ํน ๋ฌธ์ ์ด๋ค. ์์ ํ์์ผ๋ก ํ๊ฒ๋๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค. DFS๋ฅผ ์ด์ฉํด ํ์ํ๋ฉด์ ๊ฐ์ง์น๊ธฐ๋ฅผ ํด์ฃผ๋ฉด๋๋ค. ๋จผ์ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ธํด์ผ ํ๊ธฐ ๋๋ฌธ์ 2์ค for๋ฌธ์ ๋๊ฒ ๋๋ค. ์ด ๋ ๋ฐฉ๋ฌธํ๋ ๊ฒ์ ์ฒดํฌํ์ง ์์ผ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
# 1244. [S/W ๋ฌธ์ ํด๊ฒฐ ์์ฉ] 2์ผ์ฐจ - ์ต๋ ์๊ธ
def dfs(n):
global result
if n == N:
result = max(result, int("".join(map(str, num))))
return
for i in range(L-1):
for j in range(i+1, L):
num[i], num[j] = num[j], num[i]
check = int("".join(map(str, num)))
if (n, check) not in visited:
dfs(n+1)
visited.append((n, check))
num[j], num[i] = num[i], num[j]
T = int(input())
for test_case in range(1, T + 1):
st, t = map(str, input().split())
num, visited = [], []
N = int(t)
L = len(st)
result = 0
for i in st:
num.append(i)
dfs(0)
print("#{} {}".format(test_case, result))
Java ์ฝ๋
package SWEA;
import java.util.Scanner;
public class SW_1244 {
static String[] arr;
static int max, chance;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int test_case = 1 ; test_case <= T ; test_case++) {
arr = sc.next().split("");
chance = sc.nextInt();
max = 0;
if(arr.length < chance) {
chance = arr.length;
}
dfs(0, 0);
System.out.println("#" + test_case + " " + max);
}
}
static void dfs(int start, int cnt) {
if(cnt == chance) {
String result = "";
for(String s : arr)
result += s;
max = Math.max(max, Integer.parseInt(result));
return;
}
for(int i = start; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
// swap
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
dfs(i, cnt + 1);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
'๐๏ธ Algorithm > โน๏ธ SW Expert Academy [SWEA]' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
โน๏ธ[SW Expert Academy] [D4] [1226] ๋ฏธ๋ก1 (0) | 2024.03.30 |
---|---|
โน๏ธ[SW Expert Academy] [Python] [D4] [1210] Ladder1 (0) | 2024.03.15 |
โน๏ธ[SW Expert Academy] [Python] [D4] [1249] ๋ณด๊ธ๋ก (0) | 2024.03.14 |
โน๏ธ[SW Expert Academy] [Python] [D2] [1859] ๋ฐฑ๋ง ์ฅ์ ํ๋ก์ ํธ (0) | 2024.03.13 |
โน๏ธ[SW Expert Academy] [Python] [D3] [1208] Flatten (0) | 2024.03.12 |