Algorithm

[Algorithm] 전보

씬프 2021. 5. 25. 14:38
반응형

문제

어떤 나라에는 N개의 도시가 있다. 그리고 각 도시는 보내고자 하는 메시지가 있는 경우, 다른 도시로 전보를 보내서 다른 도시로 해당 메시지를 전송할 수 있다. 하지만 X라는 도시에서 Y라는 도시로 전보를 보내고자 하면, 도시 X에서 Y로 향하는 통로가 설치되어 있어야 한다. X->Y가 있지만 Y->X가 없는 경우 Y에서 X로 메시지를 보낼 수 없다.

 

어느날 C라는 도시에서 위급 상황이 발생했다. 그래서 최대한 많은 도시로 메시지를 보내고자 한다. 메시지는 도시 C에서 출발하여 각 도시 사이에 설치된 통로를 거쳐 최대한 많이 퍼져나갈 것이다. 각 도시의 번호와 통로가 설치되어 있는 정보가 주어졌을 때, 도시 C에서 보낸 메시지를 받게 되는 도시의 개수는 총 몇 개이며 도시들이 모두 메시지를 받는데까지 걸리는 시간은 얼마인지 계산하는 프로그램을 작성하시오.

 

입력 조건

첫째 줄에 도시의 개수 N, 통로의 개수 M, 메시지를 보내고자 하는 도시 C가 주어진다.

(1 <= N <= 30,000 , 1 <= M <= 200,000, 1 <= C <= N)

둘째 줄부터 M+1번째 줄까지 통로에 대한 정보 X, Y, Z가 주어진다.

이는 특정 도시 X에서 다른 도시 Y로 이어지는 통로가 있으며, 메시지가 전달되는 시간이 Z라는 의미다.

 

출력 조건

첫째줄에 도시 C에서 보낸 메시지를 받는 도시의 총 개수와 총 걸리는 시간을 출력하시오.

 

풀이

최단거리 문제로, 시작 도시에서 다른 도시들로 가는데 걸리는 최단거리를 구하는 문제. 

먼저, 다익스트라 알고리즘으로 시작 도시에서 다른 도시들까지의 최단거리를 구한다.

거리가 INF에서 갱신되어 있다면, 도착한 도시로 처리하고 (마지막에 본인 도시 제외)

제일 먼 거리에 있는 도시에 도달한 시간이 모두 메시지를 받는 시간으로 처리한다.

import java.util.*;

class Node implements Comparable<Node> {
  private int index; // 가려는 곳
  private int distance; // 가려는 곳까지의 거리

  public Node(int index, int distance) {
    this.index = index;
    this.distance = distance;
  }

  public int getIndex() {
    return this.index;
  }

  public int getDistance() {
    return this.distance;
  }

  @Override
  public int compareTo(Node other) { // 우선순위 큐를 위한 기본 정렬 기준 정의
    if (this.distance < other.getDistance()) {
      return -1;
    }
    return 1;
  }
}

class Main {
  
  public static final int INF = (int) 1e9; // 아주 큰 값
  public static int n, m, c;
  // 노드가 저장되는 2차원 리스트
  // (1번 리스트에 저장된 노드는, 1번 도시에서 다른도시로 연결된 간선 정보)
  public static ArrayList<ArrayList<Node>> graph = new ArrayList<>();
  // 거리 정보 저장
  public static int[] d = new int[30001];

  public static void dijkstra (int c) {
  
    PriorityQueue<Node> pq = new PriorityQueue<>();
    pq.offer(new Node(c, 0));
    d[c] = 0;
    
    while (!pq.isEmpty()) {
      Node node = pq.poll();
      int dist = node.getDistance();
      int now = node.getIndex();
      if (d[now] < dist) continue;
      
      for (int i = 0; i < graph.get(now).size(); i++) {
        int cost = d[now] + graph.get(now).get(i).getDistance();
        if (cost < d[graph.get(now).get(i).getIndex()]) {
          d[graph.get(now).get(i).getIndex()] = cost;
          pq.offer(new Node(graph.get(now).get(i).getIndex(), cost));
        }
      }
    }
    
  }

  public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    m = sc.nextInt();
    c = sc.nextInt();

    for (int i = 0; i <= n; i++) {
      graph.add(new ArrayList<Node>());
    }

    for (int i = 0 ; i < m; i++) {
      int a = sc.nextInt();
      int b = sc.nextInt();
      int c = sc.nextInt();
      graph.get(a).add(new Node(b, c));
    }

    Arrays.fill(d, INF);

    dijkstra(c);

    int cnt = 0;
    int maxDistance = 0;
    for (int i = 0; i <= n; i++) {
      if (d[i] != INF) {
        cnt++;
        maxDistance = Math.max(d[i], maxDistance);
      }
    }
    
    System.out.println((cnt - 1) + " " + maxDistance);

  } // end main
}

'Algorithm' 카테고리의 다른 글

[Algorithm] 팀 결성  (0) 2021.05.27
[Algorithm] 서로소 집합 자료구조  (0) 2021.05.26
[Algorithm] 미래 도시  (0) 2021.05.22
[Algorithm] 효율적인 화폐 구성  (0) 2021.05.21
[Algorithm] 바닥 공사  (0) 2021.05.20