题意题目都很简单,最小生成树,然后用并查集来判断是否已经连入图中
import java.util.PriorityQueue;
import java.util.Scanner;
class Road implements Comparable<Road>{
int a,b,dis;
public Road(int a,int b,int dis) {
this.a=a;
this.b=b;
this.dis=dis;
}
@Override
public int compareTo(Road o) {
if(dis!=o.dis) {
return dis-o.dis;
}else {
if(a!=o.a)
return a-o.a;
else
return b-o.b;
}
}
}
public class Main{
static Scanner sc = new Scanner(System.in);
static int n,m,cnt;
static int [] dad;
static PriorityQueue<Road> pq=new PriorityQueue<Road>();
static void init() {
cnt=0;
for(int i=1;i<=n;i++)
dad[i]=i;
}
static int find(int x) {
if(x==dad[x]) return x;
else {
dad[x]=find(dad[x]);
return dad[x];
}
}
static void union(int x,int y) {
int dx=find(x);
int dy=find(y);
if(dx==dy) {return;}
if(dx>dy)
dad[dx]=dy;
else
dad[dy]=dx;
}
public static void main(String[] args) {
while(sc.hasNext()) {
n=sc.nextInt();
if(n==0) break;
dad=new int[n+1];
init();
pq.clear();
int len=n*(n-1)/2;
for(int i=0;i<len;i++) {
pq.add(new Road(sc.nextInt(),sc.nextInt(),sc.nextInt()));
}
Road tmp;
while(!pq.isEmpty()) {
tmp=pq.poll();
if(find(tmp.a)==find(tmp.b)) continue;
else {
union(tmp.a,tmp.b);
cnt+=tmp.dis;
}
}
System.out.println(cnt);
}
System.exit(0);
}
}