Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import static java.lang.Integer.parseInt;
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.PriorityQueue;
- import java.util.StringTokenizer;
- public class Main {
- static BufferedReader reader;
- static StringTokenizer tok;
- static int n, m;
- static long cost;
- static ArrayList<pair> graph[];
- static PriorityQueue<pair> q;
- static boolean visited[];
- public static void main(String[] args) throws IOException {
- Input();
- sol();
- }
- public static void Input() throws IOException {
- reader = new BufferedReader(new InputStreamReader(System.in));
- tok = new StringTokenizer(reader.readLine());
- n = parseInt(tok.nextToken());
- m = parseInt(tok.nextToken());
- graph = new ArrayList[n + 1];
- for (int i = 1; i <= n; i++) {
- graph[i] = new ArrayList<pair>();
- }
- for (int i = 1; i <= m; i++) {
- tok = new StringTokenizer(reader.readLine());
- int x = parseInt(tok.nextToken()), y = parseInt(tok.nextToken()), w = parseInt(tok.nextToken());
- graph[x].add(new pair(y, w));
- graph[y].add(new pair(x, w));
- }
- }
- public static void sol() {
- visited = new boolean[n + 1];
- q = new PriorityQueue<pair>(Comparator.comparing((pair obj) -> obj.weight));
- q.add(new pair(1, 0));
- visited[1] = true;
- while (!q.isEmpty()) {
- pair obj = q.poll();
- if (!visited[obj.node]) {
- visited[obj.node] = true;
- cost+=obj.weight;
- }
- for (pair x : graph[obj.node]) {
- if (!visited[x.node]) {
- q.add(x);
- }
- }
- }
- System.out.println(cost);
- }
- static class pair {
- int node, weight;
- public pair(int node, int weight) {
- this.node = node;
- this.weight = weight;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement