Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/ENCODING

 

algospot.com :: ENCODING

Encoding 문제 정보 문제 Chip and Dale have devised an encryption method to hide their (written) text messages. They first agree secretly on two numbers that will be used as the number of rows (R) and columns (C) in a matrix. The sender encodes an int

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.*;
 
public class Main {
    private static final char EMPTY = 0;
    private static final Map<Character, String> binaries = new HashMap<>();
    private static final int[][] directions = new int[][]{{01}, {10}, {0-1}, {-10}};
 
    static {
        char[] buffer = new char[]{'0''0''0''0''0'};
 
        // 케이스마다 문자를 이진수로 변환할 시, 중복계산을 없애기 위해 초기화 시 기록을 한다.
        binaries.put(' 'new String(buffer));
        for (char c = 'A'; c <= 'Z'++c) {
            int i = buffer.length - 1;
            do {
                if (buffer[i] == '0') {
                    buffer[i] = '1';
                    break;
                }
                else buffer[i--= '0';
            } while (i >= 0);
 
            binaries.put(c, new String(buffer));
        }
    }
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[][] board = new char[20][20];
 
        int cases = scanner.nextInt();
        for (int n = 1; n <= cases; ++n) {
            int r = scanner.nextInt(), c = scanner.nextInt(), y = 0, x = 0, directionIndex = 0;
            String line = scanner.nextLine().trim();
            for (char character : line.toCharArray()) {
                for (char digit : binaries.get(character).toCharArray()) {
                    board[y][x] = digit;
 
                    int[] direction = directions[directionIndex];
                    if (outOfBoard(y + direction[0], r)
                            || outOfBoard(x + direction[1], c)
                            || board[y + direction[0]][x + direction[1]] != EMPTY) {
                        directionIndex = (directionIndex + 1) % directions.length;
                        direction = directions[directionIndex];
                    }
                    y += direction[0];
                    x += direction[1];
                }
            }
 
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    builder.append(board[i][j] == EMPTY ? '0' : board[i][j]);
                    board[i][j] = EMPTY;
                }
            }
 
            System.out.printf("%d %s\n", n, builder);
        }
    }
 
    private static boolean outOfBoard(int value, int max) {
        return value < 0 || value >= max;
    }
}
cs


이 문제는 아래 문제와 짝을 이루는 문제로, 안내에 따라 문자를 Encoding 합니다. 

 

[DECODE] Decoding


주요 살펴볼 사항은 총 두가지입니다. 

 

1. 제한된 이진수 변환을 빠르게 하기 위해, 초기화 과정을 수행했습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
 
public class Main {
   static {
        char[] buffer = new char[]{'0''0''0''0''0'};
 
        // 케이스마다 문자를 이진수로 변환할 시, 중복계산을 없애기 위해 초기화 시 기록을 한다.
        binaries.put(' 'new String(buffer));
        for (char c = 'A'; c <= 'Z'++c) {
            int i = buffer.length - 1;
            do {
                if (buffer[i] == '0') {
                    buffer[i] = '1';
                    break;
                }
                else buffer[i--= '0';
            } while (i >= 0);
 
            binaries.put(c, new String(buffer));
        }
    }
}
cs

 

 

2. 나선모양으로 변경하기 위해, 4가지 방향에 대한 상대좌표를 이용하도록 하였습니다.

 

1
    private static final int[][] directions = new int[][]{{01}, {10}, {0-1}, {-10}};
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[MISPELL] Mispelling  (0) 2022.01.06
[DIAMOND] 다이아몬드  (0) 2022.01.06
[CANDLESTICK] Candlestick Charts  (0) 2022.01.06
[KAKURO1] Kakuro I  (0) 2022.01.06
[FESTIVAL] 록 페스티벌  (0) 2022.01.06
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/CANDLESTICK

 

algospot.com :: CANDLESTICK

Candlestick Charts 문제 정보 문제 A candlestick chart, often abbreviated to candle chart, is a variation of a bar chart. It is mostly used to describe the price of a stock over time. You are using a simple candle chart which looks like above. Each ba

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[][] intervals = new int[2000][2];
 
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int n = scanner.nextInt();
            for (int i = 0; i < n; ++i) {
                intervals[i][0= scanner.nextInt();
                intervals[i][1= scanner.nextInt();
            }
 
            int ret = 0;
            for (int i = 0; i < n; ++i) {
                int min = -1, max = Integer.MAX_VALUE;
                for (int day = 0, maxDay = n - i; day < maxDay; ++day) {
                    min = Math.max(min, intervals[i + day][0]);
                    max = Math.min(max, intervals[i + day][1]);
 
                    ret = Math.max(ret, (day + 1* (max - min));
                }
            }
            System.out.println(ret);
        }
    }
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[DIAMOND] 다이아몬드  (0) 2022.01.06
[ENCODING] Encoding  (0) 2022.01.06
[KAKURO1] Kakuro I  (0) 2022.01.06
[FESTIVAL] 록 페스티벌  (0) 2022.01.06
[NOTE] Note  (0) 2022.01.06
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/KAKURO1

 

algospot.com :: KAKURO1

Kakuro I 문제 정보 문제 카쿠로는 흔히 십자말풀이 수학 버전이라고 불리는 논리 퍼즐이다. 카쿠로는 위와 같이 생긴 정사각형의 게임판을 가지고 하는 퍼즐로, 이 게임판의 각 칸은 흰 칸이거나,

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Answer> answers = new ArrayList<>();
        int[][] board = new int[20][20], directions = new int[][] {{01}, {10}};
 
        int cases = scanner.nextInt();
        System.out.println(cases);
        while (cases-- > 0) {
            int n = scanner.nextInt();
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    board[i][j] = scanner.nextInt();
                }
            }
            for (int i = 0, len = directions.length; i < len; ++i) {
                int[] direction = directions[i];
                for (int j = 0; j < n; ++j) {
                    for (int k = 0; k < n; ++k) {
                        if (board[j][k] != 0continue;
 
                        int ret = 0, y = j + direction[0], x = k + direction[1];
                        while (y < n && x < n && board[y][x] != 0) {
                            ret += board[y][x];
                            y += direction[0];
                            x += direction[1];
                        }
                        if (ret != 0) answers.add(new Answer(j + 1, k + 1, i, ret));
                    }
                }
            }
 
            System.out.println(n);
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    System.out.printf("%d%c", (board[i][j] == 0) ? 0 : 1, (j == n - 1) ? '\n' : ' ');
                }
            }
            System.out.println(answers.size());
            for (Answer answer : answers) System.out.println(answer);
            answers.clear();
        }
    }
 
    private static final class Answer {
        final int y, x, direction, value;
 
        public Answer(int y, int x, int direction, int value) {
            this.y = y;
            this.x = x;
            this.direction = direction;
            this.value = value;
        }
 
        @Override
        public String toString() {
            return String.format("%d %d %d %d", y, x, direction, value);
        }
    }
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[ENCODING] Encoding  (0) 2022.01.06
[CANDLESTICK] Candlestick Charts  (0) 2022.01.06
[FESTIVAL] 록 페스티벌  (0) 2022.01.06
[NOTE] Note  (0) 2022.01.06
[MAGICPOWER] 마력  (0) 2022.01.05
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/FESTIVAL

 

algospot.com :: FESTIVAL

록 페스티벌 문제 정보 문제 커다란 공연장을 빌려서 록 페스티벌을 개최하려고 합니다. 이 페스티벌은 여러 날 동안 진행되며, 하루에 한 팀의 밴드가 공연장에서 콘서트를 하게 됩니다. 전체

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        int[][] caches = new int[1000][1000];
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int n = scanner.nextInt(), l = scanner.nextInt();
            for (int i = 0; i < n; ++i) {
                caches[0][i] = (i == 0) ? scanner.nextInt() : caches[0][i - 1+ scanner.nextInt();
            }
 
            for (int i = 1; i < n; ++i) {
                for (int j = i; j < n; ++j) {
                    // i일부터 (j-i+1)일 연속 공연했을 때의 총 비용
                    caches[i][j] = caches[i - 1][j] - caches[i - 1][i - 1];
                }
            }
 
            double ret = Double.MAX_VALUE;
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    int len = j - i + 1;
                    if (len >= l) ret = Math.min(ret, ((double) caches[i][j]) / len);
                }
            }
 
            System.out.printf("%.8f\n", ret);
        }
    }
}
cs

 

최소 평균 비용을 알기 위해, 모든 경우의 수를 탐색해 보는 것을 고민해봤습니다. 

i일부터 연속 (n-i+1)일 간의 총 비용을 구한 뒤, 최소 평균을 구하도록 되어 있습니다. 

해당 요구사항은 파스칼의 삼각형과 같이 처음부터 모든 덧셈을 하는 것이 아닌 일련의 점화식을 만들면 제곱 시간안에 구해볼 수 있습니다.


이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[CANDLESTICK] Candlestick Charts  (0) 2022.01.06
[KAKURO1] Kakuro I  (0) 2022.01.06
[NOTE] Note  (0) 2022.01.06
[MAGICPOWER] 마력  (0) 2022.01.05
[DECODE] Decoding  (0) 2022.01.05
Posted by N'

C 로 풀어보는 알고리즘입니다. 📖 

(이번 문제는 Java 를 이용할 시, input 과정 중 시간초과를 발생시키는 요소가 있는 것 같아 보입니다.)
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/NOTE

 

algospot.com :: NOTE

Note 문제 정보 문제 C major scale consists of 8 tones: c d e f g a b C. For this task we number the notes using numbers 1 through 8. The scale can be played ascending, from 1 to 8, descending, from 8 to 1, or mixed. Write a program that, given the se

www.algospot.com


풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#define ASC 0
#define DESC 1
#define MIX 2
 
int main()
{
    int oldValue, newValue, ret = MIX;
    for (int i = 0; i < 8++i)
    {
        scanf("%d"&newValue);
        if (i == 0)
        {
            if (newValue == 1 || newValue == 8)
            {
                ret = (newValue == 1) ? ASC : DESC;
                oldValue = newValue;
            }
        }
        else
        {
            switch (ret)
            {
            case ASC:
                ret = (newValue - oldValue == 1) ? ASC : MIX;
                break;
 
            case DESC:
                ret = (oldValue - newValue == 1) ? DESC : MIX;
                break;
            }
 
            oldValue = newValue;
        }
    }
 
    switch (ret)
    {
    case ASC:
        printf("ascending\n");
        break;
 
    case DESC:
        printf("descending\n");
        break;
 
    case MIX:
        printf("mixed\n");
        break;
    }
 
    return 0;
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[KAKURO1] Kakuro I  (0) 2022.01.06
[FESTIVAL] 록 페스티벌  (0) 2022.01.06
[MAGICPOWER] 마력  (0) 2022.01.05
[DECODE] Decoding  (0) 2022.01.05
[FIX] 문제 순서는 난이도 순이 아닙니다  (0) 2022.01.05
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/MAGICPOWER

 

algospot.com :: MAGICPOWER

마력 문제 정보 문제 KAIST에는 우리가 모르는 전설의 마법사(!)가 살고 있다. 전설의 마법사는 아이템을 사용해서 마력을 보충하는데, 아이템에 쓰여 있는 수만큼 마력을 얻을 수 있다고 한다. 그

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;
 
public class Main {
    private static final int[] items = new int[100];
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int n = scanner.nextInt(), m = scanner.nextInt();
            for (int i = 0; i < n; ++i) items[i] = scanner.nextInt();
 
            int ret = 0;
            while (m-- > 0) {
                int maxIndex = maxIndexOf(n);
                int maxValue = items[maxIndex];
                ret += maxValue;
                items[maxIndex] = Math.max(maxValue - 10);
            }
 
            System.out.println(ret);
        }
    }
 
    private static int maxIndexOf(int n) {
        int ret = 0, max = 0;
        for (int i = 0; i < n; ++i) {
            if (max >= items[i]) continue;
            max = items[i];
            ret = i;
        }
 
        return ret;
    }
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[FESTIVAL] 록 페스티벌  (0) 2022.01.06
[NOTE] Note  (0) 2022.01.06
[DECODE] Decoding  (0) 2022.01.05
[FIX] 문제 순서는 난이도 순이 아닙니다  (0) 2022.01.05
[CSBASEBALL] 각본 없는 야구  (0) 2022.01.05
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/DECODE

 

algospot.com :: DECODE

Decoding 문제 정보 문제 Chip and Dale have devised an encryption method to hide their (written) text messages. They first agree secretly on two numbers that will be used as the number of rows (R) and columns (C) in a matrix. The sender encodes an int

www.algospot.com


풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.*;
 
public class Main {
    private static final int USE = -1;
    private static final int[][] directions = new int[][]{{01}, {10}, {0-1}, {-10}};
 
    public static void main(String[] args) {
        int[] acc = new int[5];
        int[][] boards = new int[20][20];
        Scanner scanner = new Scanner(System.in);
 
        int cases = scanner.nextInt();
        for (int i = 1; i <= cases; ++i) {
            int r = scanner.nextInt(), c = scanner.nextInt();
            char[] matrix = scanner.next().toCharArray();
            for (int j = 0, len = matrix.length; j < len; ++j) boards[j / c][j % c] = matrix[j] - '0';
 
            System.out.printf("%d %s\n", i, getDecode(boards, acc, r, c));
        }
    }
 
    private static String getDecode(int[][] boards, int[] acc, int r, int c) {
        StringBuilder builder = new StringBuilder();
        int y = 0, x = 0, accLength = 0, directionIndex = 0;
        do {
            acc[accLength++= boards[y][x];
            boards[y][x] = USE;
            if (accLength == 5) {
                accLength = 0;
                builder.append(toString(toDecimal(acc)));
            }
 
            if (isMovable(boards, r, c, y, x, directionIndex)
                    || isMovable(boards, r, c, y, x, directionIndex = (directionIndex + 1) % 4)) {
                y += directions[directionIndex][0];
                x += directions[directionIndex][1];
            } else {
                y = x = -1;
            }
        } while (y != -1);
 
        return builder.toString();
    }
 
    private static int toDecimal(int[] acc) {
        return 16 * acc[0+ 8 * acc[1+ 4 * acc[2+ 2 * acc[3+ acc[4];
    }
 
    private static String toString(int decimal) {
        return (decimal == 0) ? " " : String.format("%c",  'A' + (decimal - 1));
    }
 
    private static boolean isMovable(int[][] boards, int r, int c, int y, int x, int directionIndex) {
        int curY = y + directions[directionIndex][0], curX = x + directions[directionIndex][1];
        if (curY < 0return false;
        if (curY >= r) return false;
        if (curX < 0return false;
        if (curX >= c) return false;
        return boards[curY][curX] != USE;
    }
}
cs

 

나선모양으로 이진수를 읽은 뒤, 10진수로 변경 후, 문제에 주어진 방식처럼 문자로 변경하면 해결할 수 있는 문제입니다. 

나선모양으로 변경하기 위해 각 방향에 대한 이동 처리를 코드로 구현한 것이 아닌, 4가지 방향에 대한 상대좌표를 이용하도록 하였습니다.

 

1
    private static final int[][] directions = new int[][]{{01}, {10}, {0-1}, {-10}};
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[NOTE] Note  (0) 2022.01.06
[MAGICPOWER] 마력  (0) 2022.01.05
[FIX] 문제 순서는 난이도 순이 아닙니다  (0) 2022.01.05
[CSBASEBALL] 각본 없는 야구  (0) 2022.01.05
[TSP1] Traveling Salesman Problem 1  (0) 2022.01.04
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/FIX

 

algospot.com :: FIX

문제 순서는 난이도 순이 아닙니다 문제 정보 문제 알고리즘 문제를 푸는 프로그래밍 대회에서, 문제 순서는 난이도와 관계가 없다. 이 문제는 앞에서부터 풀다가 뒤쪽에 있는 쉬운 문제를 놓치

www.algospot.com

 

풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int n = scanner.nextInt(), count = 0;
            for (int i = 1; i <= n; ++i) if (scanner.nextInt() == i) ++count;
 
            System.out.println(count);
        }
    }
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[MAGICPOWER] 마력  (0) 2022.01.05
[DECODE] Decoding  (0) 2022.01.05
[CSBASEBALL] 각본 없는 야구  (0) 2022.01.05
[TSP1] Traveling Salesman Problem 1  (0) 2022.01.04
[NQUEEN] N-Queen  (0) 2022.01.04
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/CSBASEBALL

 

algospot.com :: CSBASEBALL

각본 없는 야구 문제 정보 문제 현재 CS 야구팀과 화나 핀토스(Hwana Pintos)팀의 야구 경기가 진행 중이다. 지금은 CS 야구팀의 공격 상황. 주자는 아무도 없지만 이들은 계속 안타(1루타)를 치기 시

www.algospot.com


풀이입니다. 🤔

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int a = scanner.nextInt(), b = scanner.nextInt();
            int diff = b - a;
            System.out.println(diff >= 0 ? 4 + diff : 0);
        }
    }
}
cs

 


이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[DECODE] Decoding  (0) 2022.01.05
[FIX] 문제 순서는 난이도 순이 아닙니다  (0) 2022.01.05
[TSP1] Traveling Salesman Problem 1  (0) 2022.01.04
[NQUEEN] N-Queen  (0) 2022.01.04
[FIXPAREN] Mismatched Parenthesis  (0) 2022.01.04
Posted by N'

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/TSP1

 

algospot.com :: TSP1

Traveling Salesman Problem 1 문제 정보 문제 NP-Complete 문제의 가장 유명한 예 중 하나인 여행하는 외판원 문제 (Traveling Salesman Problem) 은, 여러 개의 도시와 그 도시 간의 거리가 주어졌을 때, 각 도시를

www.algospot.com


풀이입니다. 🤔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
 
public class Main {
    private static final double[][] distances = new double[8][8];
    private static final boolean[] visited = new boolean[8];
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            int n = scanner.nextInt();
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    distances[i][j] = scanner.nextDouble();
                }
            }
 
            System.out.printf("%.10f\n", getMinVisitDistance(n));
            Arrays.fill(visited, false);
        }
    }
 
    private static double getMinVisitDistance(int n) {
        double ret = Double.MAX_VALUE;
        for (int i = 0; i < n; ++i) {
            visited[i] = true;
            ret = Math.min(ret, getMinVisitDistance(n, i, 1)); // 시작하는 도시마다, 총 방문거리가 달라질 수 있다.
            visited[i] = false;
        }
 
        return ret;
    }
 
    private static double getMinVisitDistance(int n, int cur, int visitedCount) {
        if (visitedCount >= n) return 0// 기저사례 : 모든 도시를 방문
 
        double ret = Double.MAX_VALUE;
        for (int i = 0; i < n; ++i) {
            if (cur == i) continue;
            if (visited[i]) continue;
 
            visited[i] = true;
            ret = Math.min(ret, distances[cur][i] + getMinVisitDistance(n, i, visitedCount + 1));
            visited[i] = false;
        }
 
        return ret;
    }
}
cs


이 풀이는 기존에 풀었던 아래 문제와 유사합니다.

 

[PICNIC] 피크닉


완전탐색으로 도시를 방문하는 모든 순서에 따라 총 거리를 구한 뒤, 최소 값을 출력하도록 합니다. 
이 방법은 가장 비효율적이며 도시의 수가 적기 때문(최대 8개)에 가능한 방법입니다.

추 후 메모이제이션을 이용하여 더 빠르게 정답을 구할 수 있는 방법을 소개해보도록 하겠습니다.

 

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

 

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[FIX] 문제 순서는 난이도 순이 아닙니다  (0) 2022.01.05
[CSBASEBALL] 각본 없는 야구  (0) 2022.01.05
[NQUEEN] N-Queen  (0) 2022.01.04
[FIXPAREN] Mismatched Parenthesis  (0) 2022.01.04
[BRACKETS2] Mismatched Brackets  (0) 2022.01.03
Posted by N'