题目描述
明明迷上了一个搭建电路的游戏。
在游戏中,每次在两个电子元件之间增加一条有效电路(两个元件之间先前没有电路相连)都将获得相应的积分奖励。
已知电子元件数量n和部分电子元件之间的奖励积分值。如何构建一个有效电路将所有元件全部连接起来,并且可以得到最多的积分奖励。
输入
每组输入数据包含m+1行。
第1行输入两个正整数n和m,其中n表示电子元件数量(n<=100),m表示提供了m对电子元件之间的奖励积分值(m<=1000)。两个正整数之间用空格隔开。
第2行到第m+1行对应m对电子元件及其对应的奖励积分值,每一行包含三个正整数,第1个和第2个整数表示电子元件编号(从1开始),第3个整数表示两个元件之间搭建电路的奖励积分num(num<1e9)。整数之间用空格隔开。
输出
每组输出占1行,输出一个正整数,即最多可以得到的积分奖励值。如果没有办法把所有元件全部连接起来,则输出“No solution.”。
样例输入
3 3
1 2 10
1 3 20
2 3 30
样例输出
50
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
static int pa[];
static int rank[];
static long num;
static class tree implements Comparable<tree> {
int x;
int y;
long w;
@Override
public int compareTo(tree o) {
// TODO Auto-generated method stub
return Long.compare(o.w, w);
}
tree(int x,int y,long w){
this.x=x;
this.y=y;
this.w=w;
}
}
static int find_set(int x) {//路径压缩查找
if(x!=pa[x]) {
pa[x]=find_set(pa[x]);
}
return pa[x];
}
static boolean union_set(int x,int y,long w) {
x=find_set(x);
y=find_set(y);
if(x==y) {
return false;
}
if(rank[x]>rank[y]) {
pa[y]=x;
} else {
if(rank[x]==rank[y]) rank[y]++;
pa[x]=y;
}
num+=w;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
pa=new int[105];
rank=new int[105];
for(int i=1;i<=n;i++) {
pa[i]=i;
rank[i]=0;
}
num=0;
List<tree>trees=new ArrayList<tree>();
for(int i=0;i<m;i++) {
trees.add(new tree(sc.nextInt(), sc.nextInt(), sc.nextLong()));
}
Collections.sort(trees);
int ans=0;
for(tree t:trees) {
int x=t.x;
int y=t.y;
long w=t.w;
boolean result=union_set(x, y, w);
if(result) {
ans++;
}
}
if(ans!=n-1)System.out.println("No solution.");
else System.out.println(num);
}
}
记得开long,不然可能会报91