Advertisement
FahimFaisal

Contest3_corona_success

Mar 10th, 2020
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class solution {
  4.  public static int[][] graph ;
  5.     public static int[] parent;  
  6.     public static int[] distance ;  
  7.     public static boolean[] check ;
  8.    
  9.     public static void main(String[] args) {
  10.         // TODO code application logic here
  11.         Scanner sc = new Scanner (System.in);
  12.             int a = sc.nextInt();
  13.             int b = sc.nextInt();
  14.              graph = new int [a] [a];
  15.              parent =new int [a];  
  16.              distance = new int [a];  
  17.              check = new boolean[a];
  18.             for(int i = 0 ; i <graph.length ;i++){
  19.                 for (int j = 0 ; j <graph.length;j++){
  20.                     graph[i][j]=-1;
  21.                 }
  22.             }
  23.              for(int i = 0 ; i < b ; i++){
  24.                  int u = sc.nextInt();
  25.                  int v = sc.nextInt();
  26.                  graph[u][v] = sc.nextInt();
  27.              }
  28.        
  29.            
  30.        
  31.     dij(graph,0);
  32.    
  33.         for(int i = 1 ; i < distance.length ; i++){
  34.             System.out.println(distance[i]);
  35.         }
  36.     }
  37.    
  38.    
  39.     public static void dij(int[][] graph, int s){
  40.         for (int i = 0 ; i < graph.length ; i++){
  41.             distance[i] =100000000;
  42.             parent[i] = -1;
  43.             check[i] = false;
  44.         }
  45.      
  46.         distance[s] = 0;
  47.        
  48.        
  49.  
  50.         for(int i = 0 ; i < graph.length ; i++){
  51.             int minKey = min(distance , check);
  52.             check[minKey] = true;
  53.             for(int j = 0 ; j < graph.length ; j++){
  54.                  if (!check[j] && graph[minKey][j]!=-1 &&  distance[minKey]+graph[minKey][j] < distance[j]) {
  55.                     parent[j] = minKey;
  56.                     distance[j] = distance[minKey] + graph[minKey][j];
  57.                 }
  58.             }
  59.         }
  60.  
  61.     }
  62.  
  63.     public static int min (int[] key , boolean[] check){
  64.         int min = 100000000 , minIndex = -1 ;
  65.         for(int i = 0 ; i <key.length ; i++){
  66.             if(check[i] == false && key[i] < min){
  67.                 min = key[i];
  68.                 minIndex = i;
  69.             }
  70.         }
  71.         return minIndex;
  72.     }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement