其他分享
首页 > 其他分享> > 最小生成树【克鲁斯卡尔】【并查集】

最小生成树【克鲁斯卡尔】【并查集】

作者:互联网

package lanqiao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MinTree {
	static int[] parents;
	static int[] ranks;
	public static void main(String[] args) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String[] s = reader.readLine().split(" ");
		int amtNode = Integer.parseInt(s[0]);
		parents = new int[amtNode+1];
		Arrays.fill(parents, -1);
		ranks = new int[amtNode+1];
		Arrays.fill(ranks, 0);
		int amtEdges = Integer.parseInt(s[1]);
		List<node> list = new ArrayList<>();
		for(int i=0;i<amtEdges;i++) {
			String[] t = reader.readLine().split(" ");
			int u = Integer.parseInt(t[0]);
			int v = Integer.parseInt(t[1]);
			int w = Integer.parseInt(t[2]);
			list.add(new node(u,v,w));
		}
		reader.close();
		Collections.sort(list);
//		System.out.println(list);
		int ans = 0;
		int ant = 0;
		for(node n:list) {
//			System.out.println(n);
			if(union(n.u,n.v)) {
				ant++;
				ans +=n.w;
			}
		}
		if(ant == amtNode-1)
		System.out.println(ans);
		else System.out.println("orz");
	}
	static int find(int x) {
		int root = x;
		while(parents[root]!=-1) {
			root = parents[root];
		}
		return root;
	}
	static boolean union(int x,int y) {
		int xRoot = find(x);
		int yRoot = find(y);
		if(xRoot == yRoot) return false;
		else {
			if(ranks[xRoot]>ranks[yRoot]) {
				parents[yRoot] = xRoot;
			}else if(ranks[xRoot]<ranks[yRoot]) {
				parents[xRoot] = yRoot;
			}else {
				parents[yRoot] = xRoot;
				ranks[yRoot]++;
			}
		}
		return true;
	}
}
class node implements Comparable<node>{
	int u;
	int v;
	int w;
	public node(int u2, int v2, int w2) {
		// TODO Auto-generated constructor stub
		this.u=u2;
		this.v=v2;
		this.w=w2;
	}
	@Override
	public int compareTo(node o) {
		// TODO Auto-generated method stub
		return Integer.compare(this.w, o.w);
	}
	@Override
	public String toString() {
		return "node [u=" + u + ", v=" + v + ", w=" + w + "]";
	}
	
}

 

标签:java,int,查集,克鲁斯,parents,卡尔,new,import,public
来源: https://www.cnblogs.com/daweiguo/p/16120601.html