用的并查集和优先队列去解的。
其实就是Kruskal算法。
最小生成树问题。
package csp2014_12_4;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
class Edge implements Comparable<Edge>{
int s,e,cost;
Edge(int a,int b,int c){
s=a;e=b;cost=c;
}
public Edge() {}
@Override
public int compareTo(Edge o) {
if(this.cost-o.cost==0) return this.s-o.s;
return this.cost-o.cost;
}
}
public class Main{
static Queue<Edge> q = new PriorityQueue<Edge>();
static int pre[];
static int find(int x){
if(pre[x]==x) return x;
else return pre[x] = find(pre[x]);
}
static void link(int x,int y){
int xx = find(x);
int yy = find(y);
if(xx>yy) pre[xx] = yy;
else pre[yy] = pre[xx];
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
q.add(new Edge(a,b,c));
}
pre = new int[n+1];
for (int i = 0; i < pre.length; i++) {
pre[i] = i;
}
int ans = 0;
Edge temp = new Edge();
whil