Pagini recente » Cod sursa (job #2588127) | Cod sursa (job #1074922) | Cod sursa (job #365665) | Cod sursa (job #485119) | Cod sursa (job #2288070)
package ACMCodeLibrary.GraphAlgorithms;
import java.util.*;
public class Dijkstra {
private int N;
private List<WeightedEdge>[] adjacencyList;
static class WeightedEdge implements Comparable<WeightedEdge> {
int to;
double weight;
public WeightedEdge(int to, double weight) {
this.to = to;
this.weight = weight;
}
@Override
public int compareTo(WeightedEdge weightedEdge) {
return Double.compare(weight, weightedEdge.weight);
}
}
private static class WeightedVertex implements Comparable<WeightedVertex> {
int index;
double weight;
int parent = -1;
public WeightedVertex(int index, double weight) {
this.index = index;
this.weight = weight;
}
@Override
public int compareTo(WeightedVertex weightedEdge) {
return Double.compare(weight, weightedEdge.weight);
}
}
public Dijkstra(int N, List<WeightedEdge>[] adjacencyList) {
this.N = N;
this.adjacencyList = adjacencyList;
}
// Dijkstra algorithm for vertex i, 0 <= i < N
public double[] dijkstra(int i) {
BitSet seen = new BitSet(N);
PriorityQueue<WeightedVertex> q = new PriorityQueue<>();
q.add(new WeightedVertex(0, i));
double[] optimal = new double[N];
Arrays.fill(optimal, Double.MAX_VALUE);
optimal[i] = 0.0;
while (seen.cardinality() < N) {
WeightedVertex curr = q.poll();
if (!seen.get(curr.index)) {
seen.set(curr.index);
for (WeightedEdge e: adjacencyList[curr.index]) {
if (e.to != curr.parent) {
if (optimal[e.to] > optimal[curr.index] + e.weight) {
optimal[e.to] = optimal[curr.index] + e.weight;
q.add(new WeightedVertex(e.to, optimal[e.to]));
}
}
}
}
}
return optimal;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); int E = sc.nextInt();
List<WeightedEdge>[] adjList = new List[N];
for (int i = 0; i < N ;i++) {
adjList[i] = new ArrayList<WeightedEdge>();
}
for (int i = 0; i < E; i++) {
int from = sc.nextInt() - 1; int to = sc.nextInt() - 1; double weight = sc.nextDouble();
adjList[from].add(new WeightedEdge(to, weight));
adjList[to].add(new WeightedEdge(from, weight));
}
Dijkstra dij = new Dijkstra(N, adjList);
double[] distances = dij.dijkstra(0);
for (int i = 1; i < N; i++) System.out.print((int)distances[i] + ' ');
}
}