diff options
Diffstat (limited to 'src/main')
-rw-r--r-- | src/main/Dijkstra.java | 64 | ||||
-rw-r--r-- | src/main/PlayGround.java | 13 |
2 files changed, 77 insertions, 0 deletions
diff --git a/src/main/Dijkstra.java b/src/main/Dijkstra.java new file mode 100644 index 0000000..5bc31b0 --- /dev/null +++ b/src/main/Dijkstra.java @@ -0,0 +1,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)); + } +}
\ No newline at end of file diff --git a/src/main/PlayGround.java b/src/main/PlayGround.java new file mode 100644 index 0000000..14a4c80 --- /dev/null +++ b/src/main/PlayGround.java @@ -0,0 +1,13 @@ +import java.util.PriorityQueue; +import java.util.HashMap; +public class PlayGround { + static int testPriorityQueue() { + PriorityQueue<Integer> numbers = new PriorityQueue<>(); + numbers.add(7); + numbers.add(5); + numbers.add(8); + numbers.add(3); + return numbers.poll(); + } + +} |