Home AtCoder. 013 Passing(5)
Post
Cancel

AtCoder. 013 Passing(5)

[Link] https://AtCoder.jp/contests/typical90/tasks/typical90_m


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
import java.util.*;
import java.io.*;

public class Main{
  static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  static StringTokenizer st;
  static ArrayList<HashMap<Integer, Integer>> al;
  static int n, m;
  static PriorityQueue<Node> q = new PriorityQueue<>();
  public static void main(String[] args) throws IOException {
    StringBuilder sb = new StringBuilder();
    readLine();
    n = getInt();
    m = getInt();
    al = new ArrayList<>();
    for(int i = 0; i <= n; i++) {
      al.add(new HashMap<>());
    }
    for(int i = 0; i < m; i++) {
      readLine();
      int t1 = getInt(), t2 = getInt(), cost = getInt();
      al.get(t1).put(t2, cost);
      al.get(t2).put(t1, cost);
    }
    long[] dp1 = dijkstra(1);
    long[] dpN = dijkstra(n);

    for(int i = 1; i <= n; i++) sb.append(dp1[i] + dpN[i] + "\n");
    System.out.print(sb);
  }

  static long[] dijkstra(int idx) {
    boolean[] visited = new boolean[n + 1];
    long[] dp = new long[n + 1];
    Arrays.fill(dp, Long.MAX_VALUE);
    dp[idx] = 0;
    q.add(new Node(idx, 0));
    while(!q.isEmpty()) {
      Node node = q.poll();
      visited[node.vertex] = true;
      if(dp[node.vertex] < node.cost) continue;
      for(Map.Entry<Integer, Integer> entry : al.get(node.vertex).entrySet()) {
        int desV = entry.getKey(), cost = entry.getValue();
        if(visited[desV]) continue;
        if(dp[desV] > (long)node.cost + cost) {
          dp[desV] = node.cost + cost;
          q.add(new Node(desV, dp[desV]));
        }
      }
    }
    return dp;
  }

  static int getInt() { return Integer.parseInt(st.nextToken()); }
  static void readLine() throws IOException { st = new StringTokenizer(br.readLine()); }
}

class Node implements Comparable<Node> {
  int vertex;
  long cost;

  public Node(int v, long c) { this.vertex = v; this.cost = c; }
  public int compareTo(Node node) { return Long.compare(cost, node.cost); }
}
This post is licensed under CC BY 4.0 by the author.