Java P3366 【模板】最小生成树

洛谷题目链接

// czl
import java.util.*;
public class Main 
{
	static class Node implements Comparable<Node> {
		int x1, x2;
		int len;
		public Node(int a, int b, int c) {
			x1 = a; x2 = b; len = c;
		}
		public int compareTo(Node o) {
			return this.len - o.len; // 按边从小到大排序
		}
	}
	
	static int N = 5010, M = 200010;
	
	static int p[] = new int[N];
	static Node[] es = new Node[M]; 
	static int n, m, res;
	
	static int find(int x) {
		if(p[x] != x) p[x] = find(p[x]);
		return p[x];
	}
	
	static boolean kruskal() {
		
		Arrays.sort(es, 0, m); // 按边从小到大排序
		
		for(int i = 1; i <= n; i ++ ) p[i] = i; // 初始化并查集数组
		
		int cnt = n; // 刚开始有n个连通块
		for(int i = 0; i < m; i ++ ) {
			int a = find(es[i].x1);
			int b = find(es[i].x2);
			if(a != b) {
				p[a] = b;
				res += es[i].len;
				cnt -- ;
			}
		}
		// 最后应该只剩下一个连通块, 否则该图不连通!
		return cnt == 1;
	}
	
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for(int i = 0; i < m; i ++ ) {
        	int a = sc.nextInt();
        	int b = sc.nextInt();
        	int dist = sc.nextInt();
        	es[i] = new Node(a, b, dist);
        }
        
        if(kruskal())
        	System.out.println(res);
        else
        	System.out.println("orz");
    }
}

你可能感兴趣的:(洛谷,java,蓝桥杯,java)