summaryrefslogtreecommitdiff
path: root/src/main/Dijkstra.java
blob: 5bc31b01733376f9e85000f17c7cecdd9226bf02 (plain)
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.*;

public class Dijkstra {
    static int distance(ArrayList<Integer>[] adj, ArrayList<Integer>[] cost, int s, int t) {
        if (s == t)
            return 0;
        int[] dist = new int[adj.length];
        //int[] prev = new int[adj.length];
        boolean[] visited = new boolean[adj.length];
        for (int i = 0; i < dist.length; i++) {
            dist[i] = Integer.MAX_VALUE;
            //prev[i] = -1;
        }

        dist[s] = 0;

        PriorityQueue<Integer> vertexQ;
        vertexQ = new PriorityQueue<Integer>(Comparator.comparingInt(a -> dist[a]));
        vertexQ.add(s);

        while (!vertexQ.isEmpty()) {
            int u = vertexQ.remove();
            if (visited[u]) {
                continue;
            }
            visited[u] = true;
            if (adj[u].size() > 0) {
                for (int i = 0; i < adj[u].size(); i++) {
                    if (dist[adj[u].get(i)] > dist[u] + cost[u].get(i)) {
                        dist[adj[u].get(i)] = dist[u] + cost[u].get(i);
                        //prev[adj[u].get(i)] = u;
                        vertexQ.add(adj[u].get(i));
                    }
                }
            }
        }
        if (dist[t] == Integer.MAX_VALUE)
            return -1;
        return dist[t];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[n];
        ArrayList<Integer>[] cost = (ArrayList<Integer>[]) new ArrayList[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<Integer>();
            cost[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < m; i++) {
            int x, y, w;
            x = scanner.nextInt();
            y = scanner.nextInt();
            w = scanner.nextInt();
            adj[x - 1].add(y - 1);
            cost[x - 1].add(w);
        }
        int x = scanner.nextInt() - 1;
        int y = scanner.nextInt() - 1;
        System.out.println(distance(adj, cost, x, y));
    }
}