题目来源:
http://www.patest.cn/contests/mooc-ds/06-%E5%9B%BE6
解:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
class Edge implements Comparable<Edge>
{
private int source ;
private int target ;
private int cost ;
public Edge(int source,int target, int cost)
{
this.source = source;
this.target = target;
this.cost = cost;
}
public int getSource() {
return source;
}
public void setSource(int source) {
this.source = source;
}
public int getTarget() {
return target;
}
public void setTarget(int target) {
this.target = target;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
@Override
public int compareTo(Edge o) {
// TODO Auto-generated method stub
if(this.cost > o.cost)
return 1;
else if(this.cost == o.cost)
return 0;
else return -1;
}
@Override
public String toString() {
return "Edge [source=" + source + ", target=" + target + ", cost="
+ cost + "]";
}
}
public class Main {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt() ; //城镇数目
int M = scanner.nextInt() ; //候选道路
int totalCost=0 ;//总花费
Edge[] edges = new Edge[M] ;//所有边的集合,使用数组速度更快
HashSet<Integer> arrived = new HashSet<Integer>(); //已经到达的城镇集合
HashSet<Edge> useEdges = new HashSet<Edge>(); //最终选择的边
int[] root = new int[N+1] ;//根元素
for(int i=0;i<=N;++i)
root[i]=i;
//M次输入
for(int i=0;i<M;i++)
{
int source = scanner.nextInt();
int target = scanner.nextInt();
int cost = scanner.nextInt();
Edge edge = new Edge(source,target,cost);
edges[i]=edge;
}
//对所有的边排序
Arrays.sort(edges);
for(int i=0; i<M;i++)
{
Edge edge =edges[i];
int se = edge.getSource();
int tt = edge.getTarget();
if( getRoot(root,se)!=getRoot(root,tt) )//加入当前的这条边不会形成环
{
arrived.add(se);
arrived.add(tt);
totalCost = totalCost +edge.getCost();
useEdges.add(edge);
int rootT = getRoot(root,tt);
int rootS = getRoot(root,se);
if(rootS >=rootT)
root[rootT]= rootS;
else
root[rootS]= rootT;
}
//System.out.println(useEdges);
if(useEdges.size()==(N-1)) // 如果所有城市都连通了
{
System.out.println(totalCost);
return ;
}
}
System.out.println(-1);
}
/*
* 查找element的根
* */
public static int getRoot(int[] root , int element)
{
while(root[element]!=element)
{
element = root[element];
}
return element;
}
}