2021-04-12



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

//kruskal算法变种题目
public class Solution20210412 {
    
    
    private static final int MaxN = 100000;
    private static final int MaxM = 300000;
    private static final int INF = Integer.MAX_VALUE;

    private static final int[] p = new int[MaxN + 3];
    private static final int[] head = new int[MaxN + 3];
    private static final int[] next = new int[MaxM + 3];
    private static final int[] to = new int[MaxM + 3];
    private static final int[] w = new int[MaxM + 3];

    private static PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));

    private static void init() {
    
    
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    }

    private static StreamTokenizer in;
    private static int N, M, idx;

    private static int nextInt() throws IOException {
    
    
        in.nextToken();
        return (int) in.nval;
    }

    public static void main(String[] args) throws IOException {
    
    
        init();
        int T = nextInt();
        for (int tc = 1; tc <= T; tc++) {
    
    
            N = nextInt();
            M = nextInt();
            for (int i = 0; i < M; i++) {
    
    
                int s = nextInt();
                int e = nextInt();
                int v = nextInt();
                addEdge(s, e, v);
                addEdge(e, s, v);
            }
            System.out.println("#" + tc + " " + kruskal());
            Arrays.fill(head,0);
        }
    }

    private static long kruskal() {
    
    
        Arrays.fill(p, INF);
        long sum = 0;
        p[1] = 0;
        pq.add(new int[]{
    
    1, 0});

        while (!pq.isEmpty()) {
    
    
            int[] cur = pq.poll();
            for (int i = head[cur[0]]; i != 0; i = next[i]) {
    
    
                if (w[i] < cur[1] || w[i] > p[i]) continue;
                if (w[i] < p[i]) {
    
    
                    p[i] = w[i];
                    pq.add(new int[]{
    
    to[i], w[i]});
                }
            }
        }
        for (int i = 2; i <= N; i++) {
    
    
            if (p[i] == INF) {
    
    
                return -1;
            }
            sum += p[i];
        }

        return sum;
    }

    private static void addEdge(int f, int t, int v) {
    
    
        next[idx] = head[f];
        to[idx] = t;
        w[idx] = v;
        head[f] = idx++;
    }
}

猜你喜欢

转载自blog.csdn.net/awp0011/article/details/115637272