欢迎访问我的CCF认证解题目录
题目描述
思路过程
这道题是最小生成树的题,好水啊这题,直接套就行了,都不用怎么改,这里我用的是克鲁斯卡尔算法。
注意:这道题输入量较大,使用java进行求解的话要优化一下输入,否则会超时
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static int[] father = new int[100005];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]), m = Integer.parseInt(line[1]), count = 0;
long minSum = 0;
PriorityQueue<Edge> edges = new PriorityQueue<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
return o1.cost - o2.cost; //按价钱升序
}
});
//初始化
for ( int i = 1; i < n+1; i++ ) father[i] = i;
for ( int i = 0; i < m; i++ ) {
line = br.readLine().split(" ");
edges.offer(new Edge(Integer.parseInt(line[0]), Integer.parseInt(line[1]), Integer.parseInt(line[2])));
}
while ( !edges.isEmpty() ) { //弹出最小的边,如果不成环,则边数加一
Edge temp = edges.poll();
int father1 = findFather(temp.v1), father2 = findFather(temp.v2);
if ( father1 != father2 ) { //如果父母不同,说明没有边连接
father[father1] = father2;
minSum += temp.cost;
count++;
if ( count == n-1 ) break;
}
}
System.out.println(minSum);
}
public static int findFather( int index ) { //路径压缩
if ( father[index] == index ) return index;
int temp = findFather(father[index]);
father[index] = temp;
return temp;
}
}
class Edge {
int v1,v2,cost;
public Edge(int v1, int v2, int cost) {
this.v1 = v1;
this.v2 = v2;
this.cost = cost;
}
@Override
public String toString() {
return "v1=" + v1 + ", v2=" + v2 + ", cost=" + cost;
}
}