코딩 테스트(Coding Test)/백준

[백준] 1238번 : 파티 - 자바(Java)

다문다뭉 2024. 11. 22. 01:17

Problem 🔒

문제

https://www.acmicpc.net/problem/1238

 

N개의 숫자로 구분된 각각의 마을에 한 명의 학생이 살고 있다.

어느 날 이 N명의 학생이 X (1 ≤ X ≤ N)번 마을에 모여서 파티를 벌이기로 했다. 이 마을 사이에는 총 M개의 단방향 도로들이 있고 i번째 길을 지나는데 Ti(1 ≤ Ti ≤ 100)의 시간을 소비한다.

각각의 학생들은 파티에 참석하기 위해 걸어가서 다시 그들의 마을로 돌아와야 한다. 하지만 이 학생들은 워낙 게을러서 최단 시간에 오고 가기를 원한다.

이 도로들은 단방향이기 때문에 아마 그들이 오고 가는 길이 다를지도 모른다. N명의 학생들 중 오고 가는데 가장 많은 시간을 소비하는 학생은 누구일지 구하여라.

입력

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어온다. 시작점과 끝점이 같은 도로는 없으며, 시작점과 한 도시 A에서 다른 도시 B로 가는 도로의 개수는 최대 1개이다.

모든 학생들은 집에서 X에 갈수 있고, X에서 집으로 돌아올 수 있는 데이터만 입력으로 주어진다.

출력

첫 번째 줄에 N명의 학생들 중 오고 가는데 가장 오래 걸리는 학생의 소요시간을 출력한다.

더보기

예제 입력 1

4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3

예제 출력 1

10

Approach 1 ⭕ : 다익스트라 (N+1)번 실행

  1. 임의의 노드 n에서 출발하여 도착 노드 X로 오는 거리
    • n → X 거리를 구할 때, 출발 노드가 매번 다르기 때문에 다익스트라를 N번 반복했다. (1 → X, 2 → X, …)
    • N번 반복할 때, 큐에서 꺼낸 노드가 도착 노드 X이면 반복문을 빠져나가, 모든 정점을 탐색하지 않도록 실행시간을 감소시켰다.
  2. 도착 노드 X에서 임의의 노드 n으로 돌아오는 거리
    • 다익스트라 알고리즘은 하나의 정점에서 다른 모든 정점까지의 최단 거리를 구하는 알고리즘이다.
    • 그렇기 때문에, X에서 출발하는 다익스트라 연산 1번을 통해 모두 구할 수 있다.

Approach 2 ⭕ : 다익스트라 2번 실행 ⭐

  1. 출발점에서 도착점으로 가는 거리
    • 도착점에서 출발점으로 단 한 번의 다익스트라 연산을 통해 돌아오는 거리를 구한듯이 출발점에서 도착점으로 가는 거리도 구할 수 있다.
    • 역방향 그래프를 이용하여, 간선 방향을 반대방향으로 뒤집으면 가능하다.
    • 도착점 X를 시작지점으로 두고 간선 방향을 뒤집은 역방향 그래프에서 최단 거리를 구하면 출발점에서 도착점으로 가는 최단거리가 된다.
    • 간선 방향을 뒤집었지만, 사실 출발점에서 도착점으로 가려면 같은 간선을 선택해야한다.
  2. 도착점에서 출발점으로 가는 거리
    • 도착점에서 출발하는 다익스트라 연산 1번을 통해 모두 구할 수 있다.


Solution 💡

다익스트라 (N+1)번 연산 + 불필요한 연산 감소로 실행시간 단축

public class 파티 {
    static int N, M, X, go[], come[], tmp[];
    static ArrayList<ArrayList<int[]>> list = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken())+1;
        M = Integer.parseInt(st.nextToken());
        X = Integer.parseInt(st.nextToken());

        go = new int[N]; come = new int[N]; tmp = new int[N];
        for(int i=0; i<N; i++){list.add(new ArrayList<>());}
        for(int i=0; i<M; i++){
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            int d = Integer.parseInt(st.nextToken());
            list.get(u).add(new int[]{v,d});
        }
        // 갈 때
        for(int i=1; i<N; i++){
            if(i==X) continue; // 도착 마을과 출발 마을이 같으면 무시
            Dijkstra(i, X, tmp); // i번 마을에서 출발하여 다른 마을까지 최단 경로 구하기
            go[i] = tmp[X]; // i번 마을에서 X번 마을까지 가는 최단 경로 저장
        }
        // 올 때
        Dijkstra(X, -1, come);
        int time = 0;
        for(int i=1; i<N; i++){time = Math.max(time, go[i]+come[i]);}
        System.out.println(time);
    }
    public static void Dijkstra(int start, int end, int[] result){
        PriorityQueue<int[]> q = new PriorityQueue<>((a,b)->a[1]-b[1]);
        Arrays.fill(result, Integer.MAX_VALUE);
        result[start] = 0;
        q.add(new int[]{start, 0});

        while(!q.isEmpty()){
            int[] current = q.poll();
            int curNode = current[0];
            int curCost = current[1];
            if(curNode == end) break; // 도착 정점에 방문하면 스탑
            if(curCost > result[curNode]) continue;
            for(int[] n : list.get(curNode)){
                int nextNode = n[0];
                int nextCost = curCost + n[1];
                if(nextCost < result[nextNode]){
                    result[nextNode] = nextCost;
                    q.add(new int[]{nextNode, nextCost});
                }
            }
        }
    }
}

다익스트라 2번 연산 (역방향 그래프를 곁들인)

public class 파티 {
    static int N, M, X, go[], come[];
    static ArrayList<ArrayList<int[]>> list1 = new ArrayList<>();
    static ArrayList<ArrayList<int[]>> list2 = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken())+1;
        M = Integer.parseInt(st.nextToken());
        X = Integer.parseInt(st.nextToken());

        go = new int[N]; come = new int[N];
        for(int i=0; i<N; i++){list1.add(new ArrayList<>());}
        for(int i=0; i<N; i++){list2.add(new ArrayList<>());}
        for(int i=0; i<M; i++){
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            int d = Integer.parseInt(st.nextToken());
            list1.get(u).add(new int[]{v,d});
            list2.get(v).add(new int[]{u,d}); // 역방향 그래프 저장
        }
        come = Dijkstra(X, list1);
        go = Dijkstra(X, list2);
        int time = 0;
        for(int i=1; i<N; i++){time = Math.max(time, go[i]+come[i]);}
        System.out.println(time);
    }
    public static int[] Dijkstra(int start, ArrayList<ArrayList<int[]>> list){
        int[] result = new int[N];
        PriorityQueue<int[]> q = new PriorityQueue<>((a,b)->a[1]-b[1]);
        Arrays.fill(result, Integer.MAX_VALUE);
        result[start] = 0;
        q.add(new int[]{start, 0});

        while(!q.isEmpty()){
            int[] current = q.poll();
            int curNode = current[0];
            int curCost = current[1];
            if(curCost > result[curNode]) continue;
            for(int[] n : list.get(curNode)){
                int nextNode = n[0];
                int nextCost = curCost + n[1];
                if(nextCost < result[nextNode]){
                    result[nextNode] = nextCost;
                    q.add(new int[]{nextNode, nextCost});
                }
            }
        }
        return result;
    }
}