Cod sursa(job #2064263)

Utilizator alexnekiNechifor Alexandru alexneki Data 12 noiembrie 2017 01:56:19
Problema Algoritmul lui Dijkstra Scor 90
Compilator java Status done
Runda Arhiva educationala Marime 2.33 kb
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.PriorityQueue;
 
public class Main {
 
  static int n;
  static int m;
 
  static List<Edge>[] g;
  static int[] dist;
 
  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 in = new BufferedReader(new InputStreamReader(new FileInputStream("dijkstra.in")));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("dijkstra.out")));

    String[] parts = in.readLine().split(" ");
    n = Integer.parseInt(parts[0]);
    m = Integer.parseInt(parts[1]); 
    
    g = new List[n];
    dist = new int[n];
    for (int i = 0; i < n; i++) {
      g[i] = new ArrayList<>();
      dist[i] = Integer.MAX_VALUE;
    }
  
    dist[0] = 0;
    for (int i = 0; i < m; i++) {
      parts = in.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<Integer> pq = new PriorityQueue<>(n, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return dist[o1] - dist[o2];
      }
    });
    pq.add(0);
    while (!pq.isEmpty()) {
      int node = pq.poll();
      for (Edge e : g[node]) {
        if (dist[node] + e.cost < dist[e.to]) {
          dist[e.to] = dist[node] + e.cost;
          pq.add(e.to);
        }
      }
    }
 
    for (int i = 1; i < n; i++) {
      if (dist[i] < Integer.MAX_VALUE) {
        out.write(dist[i] + " ");
      } else {
        out.write("0 ");
      }
    }
    out.close();
  } 
}