Advertisement
Guest User

DijkstraDetresse

a guest
Jan 26th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.25 KB | None | 0 0
  1. /**
  2.  * Using this template, your task is to implement functions denoted by TODO in the comments.
  3.  *
  4.  * In this task, you work with a directed weighted graph. Your task is to find the shortest
  5.  * path from u to all vertices of the graph using Dijkstra's algorithm.
  6.  *
  7.  * You can define new classes and methods and extend the existing. Just do not change the API.
  8.  *
  9.  * Find the detailed description by the methods of class Graph.
  10.  *
  11.  * The Java project also contains tests, in Eclipse you can run them by left-clicking:
  12.  * test/(default package)/JUnitTest.java and selecting Run as -> JUnitTest.java.
  13.  *
  14.  * The tests will show you if they passed/failed. In case of fail, you can see an exception
  15.  * if the code did not finished, or the difference between your output and expected output.
  16.  * The test names should help you to explain what is being tested. You can also see the content
  17.  * of the tests, for the format of the input, see <code>read</code> method.
  18.  *
  19.  * The output format is described in the comment of <code>output</code> method.
  20.  */
  21.  
  22. /**
  23.  * This imports policy applies to all programming assignments and the exam.
  24.  *
  25.  * You are forbidden to add any other import statements. Make sure that you do not leave any
  26.  * imports commented out, or that your IDE does not add any automatically. You can recognize
  27.  * allowed imports by the <code>// allowed import</code> comment.
  28.  * Calls by the fully qualified name are treated as imports as well. Those are, for example,
  29.  * <code>java.util.Arrays.sort</code>, or <code>java.util.Arrays.binarySearch</code>.
  30.  * You can use data structures we provide to you by imports, by our definitions (even
  31.  * implicitly used classes of packages, such as methods of Object those are inherited with
  32.  * every class declaration, Array, or String), or data structures that you write on your own.
  33.  * Usage of common arrays (<code>type[] variable</code>) is not restricted.
  34.  *
  35.  * Note that Judge is not enforcing this policy. So if you violate this policy, you may lose the
  36.  * bonus points even if Judge accepts your submission.
  37.  *
  38.  * The general exceptions out of this policy is the package Math. The exceptions that are specific
  39.  * to a given template are written down by its imports.
  40.  */
  41. // you can import both java.util.Comparator as well as java.lang.Comparable for this task
  42. // import java.util.PriorityQueue; // allowed import
  43. import java.util.StringTokenizer; // allowed import
  44. import java.io.BufferedReader; // allowed import
  45. import java.io.IOException; // allowed import
  46. import java.io.InputStream; // allowed import
  47. import java.io.InputStreamReader; // allowed import
  48. import java.io.PrintStream; // allowed import
  49. import java.lang.Math; // allowed import
  50.  
  51. class Main {
  52.     public static void main(String[] args) {
  53.         ReadAndWrite rw = new ReadAndWrite();
  54.         rw.readAndSolve(System.in, System.out);
  55.     }
  56. }
  57.  
  58. class PQPairs implements Comparable<PQPairs> {
  59.     int vertex;
  60.     int distance;
  61.    
  62.     public PQPairs(int v, int d) {
  63.         vertex = v;
  64.         distance = d;
  65.     }
  66.    
  67.     @Override
  68.     public int compareTo(PQPairs other) {
  69.         if(this.distance > other.distance) {
  70.             return 1;
  71.         } else if (this.distance < other.distance) {
  72.             return -1;
  73.         } else {
  74.             return 0;
  75.         }
  76.     }
  77. }
  78.  
  79. class Graph {
  80.     int[][] matrix; // directed graph represented by a distance matrix
  81.     // if you need, you can store other attributes
  82.     // for each graph, method <code>dijkstra</code> is called just once
  83.  
  84.     /**
  85.      * The class is instantiated once for every graph.
  86.      *
  87.      * Each graph contains 0 on the diagonal (distance u to u is 0)
  88.      * and <code>Integer.MAX_VALUE</code> states for a missing edge.
  89.      *
  90.      * All edge lengths are positive.
  91.      */
  92.     Graph(int n) {
  93.         matrix = new int[n][n];
  94.        
  95.         for(int i = 0; i < n; i++){
  96.             for(int  j = 0; j < n; j++){
  97.                 if(i == j){
  98.                     matrix[i][j] = 0;
  99.                 }else{
  100.                     matrix[i][j] = Integer.MAX_VALUE;
  101.                 }
  102.             }
  103.         }
  104.     }
  105.    
  106.     /**
  107.      * Inserts an edge from u to v with given weight.
  108.      */
  109.     public void addEdge(int u, int v, int weight){
  110.          if((u < 0 || u >= matrix.length) || (v < 0 || v >= matrix.length)) {
  111.              return;
  112.          }
  113.          matrix[u][v] = weight;
  114.     }
  115.    
  116.    /**
  117.     * TODO: Return an array of the shortest paths from vertex
  118.     * <code>from</code> to all vertices. That means that the
  119.     * the returned array will on position [i] contain distance
  120.     * from <code>from</code> to i.
  121.     *
  122.     * If some vertex is not reachable, return <code>Integer.MAX_VALUE</code>
  123.     * for that vertex.
  124.     */
  125.     int[] dijkstra(int from) {
  126.         PriorityQueue pq = new PriorityQueue(matrix.length);
  127.         pq.insert(new Vertex(from, 0));
  128.         int[] distances = new int[matrix.length];
  129.         for (int i = 0; i < distances.length; i++) {
  130.             if (i == from) distances[i] = 0;
  131.             else distances[i] = Integer.MAX_VALUE;
  132.         }
  133.         boolean[] processed = new boolean[matrix.length];
  134.         boolean[] discovered = new boolean[matrix.length];
  135.         discovered[0] = true;
  136.        
  137.        
  138.         while (!pq.isEmpty()) {
  139.            
  140.             Vertex u = pq.extractMin();
  141.            
  142.             if (processed[u.id]) {
  143.                 continue;
  144.             }
  145.            
  146.             processed[u.id] = true;
  147.             distances[u.id] = u.distance;
  148.            
  149.             for(int v = 0; v < matrix.length; v++) {
  150.                
  151.                 if (matrix[u.id][v] != Integer.MAX_VALUE && !processed[v]) {
  152.                    
  153.                     if (distances[v] == Integer.MAX_VALUE) {
  154.                         Vertex newVertex = new Vertex(v, distances[u.id] + matrix[u.id][v]);
  155.                         distances[v] = newVertex.distance;
  156.                         pq.insert(newVertex);
  157.                        
  158.                     }
  159.                     if (distances[v] > distances[u.id] + matrix[u.id][v]) {
  160.                         distances[v] = distances[u.id] + matrix[u.id][v];
  161.                         pq.decreaseKey(v, distances[v]);   
  162.                     }
  163.                 }
  164.             }
  165.         }
  166.        
  167.        
  168.         return distances;
  169.     }
  170.    
  171.    
  172. }
  173.  
  174. class Vertex {
  175.     int distance;
  176.     int id;
  177.    
  178.     public Vertex(int id, int v) {
  179.         this.distance = v;
  180.         this.id = id;
  181.     }
  182. }
  183.  
  184. class PriorityQueue {
  185.     Vertex[] keys;
  186.     int[] pointer;
  187.     int N;
  188.     int n;
  189.    
  190.     public PriorityQueue(int N) {
  191.         this.keys = new Vertex[N];
  192.         this.pointer = new int[N];
  193.         this.N = N;
  194.         this.n = 0;
  195.     }
  196.    
  197.     public void insert(Vertex v) {
  198.         if (n < N) {
  199.             keys[n++] = v;
  200.             pointer[v.id] = n - 1;
  201.             siftUp(n - 1);
  202.         }
  203.     }
  204.    
  205.     public Vertex extractMin() {
  206.         Vertex result = keys[0];
  207.        
  208.         swap(0, --n);
  209.         //keys[n] = null;
  210.         //pointer[result.id] = -1;
  211.         siftDown(0);
  212.        
  213.         return result;
  214.     }
  215.    
  216.     public boolean isEmpty() {
  217.         return n == 0;
  218.     }
  219.    
  220.     public void decreaseKey(int id, int newDistance) {
  221.         keys[pointer[id]].distance = newDistance;
  222.         siftUp(pointer[id]);
  223.     }
  224.    
  225.     public void siftDown(int index) {
  226.         while (leftIndex(index) < n) {
  227.             int j = leftIndex(index);
  228.            
  229.             if (j + 1 < n)
  230.                 if (keys[j].distance > keys[j + 1].distance)
  231.                     j = j+1;
  232.            
  233.             if (keys[index].distance < keys[j].distance) break;
  234.            
  235.             swap(index, j);
  236.             index = j;
  237.         }
  238.     }
  239.    
  240.     public void siftUp(int index) {
  241.         while (parentIndex(index) >= 0 && keys[parentIndex(index)].distance > keys[index].distance) {
  242.             swap(index, parentIndex(index));
  243.             index = parentIndex(index);
  244.         }
  245.     }
  246.    
  247.     public int parentIndex(int index) {
  248.         return (index + 1) / 2 - 1;
  249.     }
  250.    
  251.     public int leftIndex(int index) {
  252.         return 2*(index + 1) - 1;
  253.     }
  254.    
  255.     public int rightIndex(int index) {
  256.         return 2*(index + 1);
  257.     }
  258.    
  259.     public void swap(int i, int j) {
  260.         Vertex tmpA = keys[i];
  261.         int tmpB = pointer[i];
  262.         keys[i] = keys[j];
  263.         pointer[i] = pointer[j];
  264.         keys[j] = tmpA;
  265.         pointer[j] = tmpB;
  266.     }
  267. }
  268.  
  269.  
  270. ///////////////////////////////////////////////////////////////////////
  271. // DO NOT MODIFY THE FOLLOWING CODE, YOU CAN COMPLETELY IGNORE IT
  272. // WE MAY USE LANGUAGE CONSTRUCTS THAT YOU MAY HAVE NOT SEEN SO FAR
  273. ///////////////////////////////////////////////////////////////////////
  274.  
  275. class ReadAndWrite {
  276.     /**
  277.      * Parses input of n distance matrices
  278.      */
  279.     void readAndSolve(InputStream in, PrintStream out) {
  280.         FastReader s = new FastReader(in);
  281.  
  282.         int n = s.nextInt();
  283.        
  284.         for (int i = 0; i < n; i++) {
  285.             int vertices = s.nextInt();
  286.            
  287.             Graph g = new Graph(vertices);
  288.  
  289.             int w;
  290.             for (int u = 0; u < vertices; u++) {
  291.                 for (int v = 0; v < vertices; v++) {
  292.                     w = s.nextInt();
  293.                     if (w != -1) {
  294.                         g.addEdge(u, v, w);
  295.                     }
  296.                 }
  297.             }
  298.            
  299.             out.println(java.util.Arrays.toString(g.dijkstra(0)));
  300.         }
  301.     }
  302. }
  303.  
  304. /**
  305.  * Ignore this class please. It is used for input parsing. Source:
  306.  * https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
  307.  */
  308. class FastReader {
  309.     BufferedReader br;
  310.     StringTokenizer st;
  311.  
  312.     FastReader(InputStream in) {
  313.         br = new BufferedReader(new InputStreamReader(in));
  314.     }
  315.  
  316.     String next() {
  317.         while (st == null || !st.hasMoreElements()) {
  318.             try {
  319.                 st = new StringTokenizer(br.readLine());
  320.             } catch (IOException e) {
  321.                 e.printStackTrace();
  322.             }
  323.         }
  324.         return st.nextToken();
  325.     }
  326.  
  327.     int nextInt() {
  328.         return Integer.parseInt(next());
  329.     }
  330.  
  331.     char nextChar() {
  332.         return next().charAt(0);
  333.     }
  334.  
  335.     String nextLine() {
  336.         String str = "";
  337.         try {
  338.             str = br.readLine();
  339.         } catch (IOException e) {
  340.             e.printStackTrace();
  341.         }
  342.         return str;
  343.     }
  344. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement