Advertisement
Yahya-Ak-Ayoub

MST - Minimum Spanning Tree

Nov 7th, 2020
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import static java.lang.Integer.parseInt;
  5. import java.util.ArrayList;
  6. import java.util.Comparator;
  7. import java.util.PriorityQueue;
  8. import java.util.StringTokenizer;
  9.  
  10. public class Main {
  11.  
  12.     static BufferedReader reader;
  13.     static StringTokenizer tok;
  14.     static int n, m;
  15.     static long cost;
  16.     static ArrayList<pair> graph[];
  17.     static PriorityQueue<pair> q;
  18.     static boolean visited[];
  19.  
  20.     public static void main(String[] args) throws IOException {
  21.  
  22.         Input();
  23.         sol();
  24.     }
  25.  
  26.     public static void Input() throws IOException {
  27.         reader = new BufferedReader(new InputStreamReader(System.in));
  28.         tok = new StringTokenizer(reader.readLine());
  29.         n = parseInt(tok.nextToken());
  30.         m = parseInt(tok.nextToken());
  31.         graph = new ArrayList[n + 1];
  32.         for (int i = 1; i <= n; i++) {
  33.             graph[i] = new ArrayList<pair>();
  34.         }
  35.         for (int i = 1; i <= m; i++) {
  36.             tok = new StringTokenizer(reader.readLine());
  37.             int x = parseInt(tok.nextToken()), y = parseInt(tok.nextToken()), w = parseInt(tok.nextToken());
  38.             graph[x].add(new pair(y, w));
  39.             graph[y].add(new pair(x, w));
  40.         }
  41.  
  42.     }
  43.  
  44.     public static void sol() {
  45.  
  46.         visited = new boolean[n + 1];
  47.         q = new PriorityQueue<pair>(Comparator.comparing((pair obj) -> obj.weight));
  48.         q.add(new pair(1, 0));
  49.         visited[1] = true;
  50.  
  51.         while (!q.isEmpty()) {
  52.  
  53.             pair obj = q.poll();
  54.             if (!visited[obj.node]) {
  55.                 visited[obj.node] = true;
  56.                 cost+=obj.weight;
  57.             }
  58.             for (pair x : graph[obj.node]) {
  59.                 if (!visited[x.node]) {
  60.                     q.add(x);
  61.                 }
  62.             }
  63.  
  64.         }
  65.         System.out.println(cost);
  66.     }
  67.  
  68.     static class pair {
  69.  
  70.         int node, weight;
  71.  
  72.         public pair(int node, int weight) {
  73.             this.node = node;
  74.             this.weight = weight;
  75.         }
  76.  
  77.     }
  78.  
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement