Pagini recente » Borderou de evaluare (job #2683120) | Borderou de evaluare (job #943695) | Borderou de evaluare (job #3245446) | Borderou de evaluare (job #1999076) | Cod sursa (job #2288073)
package ACMCodeLibrary.GraphAlgorithms;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class Main {
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 Main(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) throws IOException {
Scanner sc = new Scanner("dijkstra.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));
}
Main dij = new Main(N, adjList);
double[] distances = dij.dijkstra(0);
BufferedWriter writer = new BufferedWriter(new FileWriter("dijkstra.out"));
// writer.write(str);
//
for (int i = 1; i < N; i++) {
writer.write((int)distances[i] + ' ');
}
}
}