Pagini recente » Cod sursa (job #3039990) | Cod sursa (job #2888757) | Cod sursa (job #3256735) | Cod sursa (job #1345115) | Cod sursa (job #2047701)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
static int n;
static int m;
static List<Edge>[] g;
static int[] dist;
static boolean[] vis;
static class Edge {
int to;
int cost;
Edge(int to, int cost) {
this.to = to;
this.cost = cost;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner in = new Scanner(new BufferedReader(new FileReader("dijkstra.in")));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dijkstra.out")));
n = in.nextInt();
m = in.nextInt();
g = new List[n];
dist = new int[n];
vis = new boolean[n];
// Arrays.fill(g, new ArrayList<>());
for(int i = 0; i<n; i++)
g[i] = new ArrayList<>();
Arrays.fill(dist, Integer.MAX_VALUE);
Arrays.fill(vis, false);
dist[0] = 0;
for(int i=0; i<m; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
int cost = in.nextInt();
g[from].add(new Edge(to, cost));
// out.println(from + ", " + to + ", " + cost);
}
PriorityQueue<Long> pq = new PriorityQueue<>();
pq.add(0L);
while(!pq.isEmpty()) {
long entry = pq.remove();
int node = (int) entry;
for(int j = 0; j < g[node].size(); j++) {
if(dist[node] + g[node].get(j).cost < dist[g[node].get(j).to]) {
dist[g[node].get(j).to] = dist[node] + g[node].get(j).cost;
pq.add(( (1L * dist[g[node].get(j).to]) << 32) + g[node].get(j).to);
}
}
}
for(int i=1; i<n; i++) {
if(dist[i] < Integer.MAX_VALUE)
out.print(dist[i] + " ");
else
out.print("0 ");
}
out.println();
// for(int i=0; i<n; i++) {
// out.print(i + " -> ");
// for(int j=0; j<g[i].size(); j++)
// out.print(g[i].get(j).to + ", ");
// out.println();
// }
out.close();
}
}