Cod sursa(job #2064252)

Utilizator alexnekiNechifor Alexandru alexneki Data 12 noiembrie 2017 01:27:59
Problema Algoritmul lui Dijkstra Scor 90
Compilator java Status done
Runda Arhiva educationala Marime 2.3 kb
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
 
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 {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("dijkstra.in")));
    PrintWriter out = new PrintWriter(new FileOutputStream("dijkstra.out"));

    String[] parts = br.readLine().split(" ");
    n = Integer.parseInt(parts[0]);
    m = Integer.parseInt(parts[1]);
 
    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++) {
      parts = br.readLine().split(" ");
      int from = Integer.parseInt(parts[0]) - 1;
      int to = Integer.parseInt(parts[1]) - 1;
      int cost = Integer.parseInt(parts[2]);
      g[from].add(new Edge(to, cost));
//      out.println(from + ", " + to + ", " + cost);
    }
 
    PriorityQueue<Long> pq = new PriorityQueue<>();
    pq.add(0L);
    while (!pq.isEmpty()) {
      int node = pq.poll().intValue();
      for (int j = 0; j < g[node].size(); j++) {
        int jNode = g[node].get(j).to;
        int jCost = g[node].get(j).cost;
        if (dist[node] + jCost < dist[jNode]) {
          dist[jNode] = dist[node] + jCost;
          pq.offer(((1L * dist[jNode]) << 32) + jNode);
        }
      }
    }
 
    StringBuilder sb = new StringBuilder("");
    for (int i = 1; i < n; i++) {
      if (dist[i] < Integer.MAX_VALUE) {
        sb.append(dist[i]).append(" ");
      } else {
        sb.append("0 ");
      }
    }
    out.println(sb);
    out.close();
  } 
}