๐Ÿ—๏ธ Algorithm/โน๏ธ SW Expert Academy [SWEA]

โน๏ธ[SW Expert Academy] [Python] [D3] [1244] ์ตœ๋Œ€ ์ƒ๊ธˆ

Dbswnstjd 2024. 3. 18. 01:35

๋ฌธ์ œ

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&problemLevel=4&problemLevel=5&contestProbId=AV15Khn6AN0CFAYD&categoryId=AV15Khn6AN0CFAYD&categoryType=CODE&problemTitle=&orderBy=INQUERY_COUNT&selectCodeLang=ALL&select-1=5&pageSize=10&pageIndex=1

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

ํ’€์ด

์ด ๋ฌธ์ œ๋Š” ๋ฐฑํŠธ๋ž˜ํ‚น ๋ฌธ์ œ์ด๋‹ค. ์™„์ „ํƒ์ƒ‰์œผ๋กœ ํ’€๊ฒŒ๋˜๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.  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;
            }
        }
    }
}