프로그래밍 공방

[프로그래머스] 합승 택시 요금 본문

개발/문제해결

[프로그래머스] 합승 택시 요금

hyosupsong 2021. 1. 26. 21:37

문제

programmers.co.kr/learn/courses/30/lessons/72413

 

코딩테스트 연습 - 합승 택시 요금

6 4 6 2 [[4, 1, 10], [3, 5, 24], [5, 6, 2], [3, 1, 41], [5, 1, 24], [4, 6, 50], [2, 4, 66], [2, 3, 22], [1, 6, 25]] 82 7 3 4 1 [[5, 7, 9], [4, 6, 4], [3, 6, 1], [3, 2, 3], [2, 1, 6]] 14 6 4 5 6 [[2,6,6], [6,3,7], [4,6,7], [6,5,11], [2,5,12], [5,3,20], [2,4

programmers.co.kr

문제해결방법

이 문제를 풀기 위해 먼저 Floyd Warshall 알고리즘으로 모든 정점 사이의 최단 거리 fw를 구했다.

그리고 가장 적게 택시 요금을 사용하기 위해 아래와 같이 중간에 거치는 장소 X를 정해서 모든 경우들을 계산해주었다.

S~X 까지의 거리 + X~A 까지의 거리 + X~B 까지의 거리

코드

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
package Programmers;
 
public class Solution_합승택시요금 {
 
    public static int solution(int n, int s, int a, int b, int[][] fares) {
        int answer = 0;
        int[][] fw = new int[n+1][n+1];
        for(int i=0; i<fares.length; i++) {
            int[] fare = fares[i];
            fw[fare[0]][fare[1]] = fare[2];
            fw[fare[1]][fare[0]] = fare[2];
        }
        for(int i=1; i<=n; i++) {
            for(int j=1; j<=n; j++) {
                if(i==j) fw[i][j] = 0;
                else {
                    if(fw[i][j]==0) fw[i][j] = Integer.MAX_VALUE>>2;
                }
            }
        }
        for(int k=1; k<=n; k++) {
            for(int i=1; i<=n; i++) {
                for(int j=1; j<=n; j++) {
                    if(fw[i][j]>fw[i][k]+fw[k][j]) fw[i][j]=fw[i][k]+fw[k][j]; 
                }
            }
        }
        answer = Integer.MAX_VALUE;
        for(int i=1; i<=n; i++) {
            answer = Math.min(answer, fw[s][i]+fw[i][a]+fw[i][b]);
        }
        return answer;
    }
    
    public static void main(String[] args) {
        int n = 6;
        int s = 4;
        int a = 6;
        int b = 2;
        int[][] fares = {{4110}, {3524}, {562}, {3141}, {5124}, {4650}, {2466}, {2322}, {1625}};
        System.out.println(solution(n, s, a, b, fares));
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.

'개발 > 문제해결' 카테고리의 다른 글

[백준] 1238번 : 파티  (0) 2021.01.27
[프로그래머스] 신규 아이디 추천  (0) 2021.01.27
[백준] 1010번 : 다리놓기  (0) 2021.01.26
[백준] 1766번 : 문제집  (0) 2021.01.26
OSI 7 Layer  (0) 2021.01.24