#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
int n,m;
struct node{
int a,b,c;
node(int a,int b,int c):a(a),b(b),c(c){};
};
vector<node> nodevector;
int fa[100001];
bool cmp(node node1, node node2){
return node1.c < node2.c;
}
int root(int a){
return fa[a]==a?a:fa[a]=root(fa[a]);
}
void connect(int a,int b){
int aa = root(a);
int bb = root(b);
fa[aa] = bb;
}
int main(){
scanf("%d %d",&n,&m);
int a,b,c;
for (int i = 0; i < m; ++i) {
scanf("%d %d %d",&a,&b,&c);
nodevector.push_back(node(a,b,c));
}
for (int i = 1; i <= n; ++i) {
fa[i] = i;
}
sort(nodevector.begin(),nodevector.end(),cmp);
int sum = 0;
int index = 0;
while (true){
node temp = nodevector[index];
if (root(1) == root(n)){
break;
}
if(root(temp.a) != root(temp.b)){
connect(temp.a, temp.b);
sum = max(sum,temp.c);
}
index++;
}
printf("%d\n",sum);
}
Java确实是慢了一些,Java和c++的思路一样,但是超时了。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public ArrayList<Edge> arrayList = new ArrayList<Edge>();
public Scanner input = new Scanner(System.in);
public int [] father;
public static void main(String[] args) {
new Main().run();
}
private void run() {
int m,n;
m = input.nextInt();
n = input.nextInt();
father = new int[m+1];
for (int i = 0; i < father.length; i++) {
father[i] = i;
}
for (int i = 0; i < n; i++) {
arrayList.add(new Edge(input.nextInt(),input.nextInt(),input.nextInt()));
}
Collections.sort(arrayList);
int answer = 0;
while (!arrayList.isEmpty()){
Edge temp = arrayList.get(0);
arrayList.remove(0);
int a = temp.a;
int b = temp.b;
int cost = temp.coat;
fatherconnect(a,b);
if (root(1) == root(m)){
answer = cost;
break;
}
}
System.out.println(answer);
}
private void fatherconnect(int a, int b) {
int fa = root(a);
int fb = root(b);
father[fa] = fb;
}
private int root(int a){
return a == father[a]?a:(father[a]=root(father[a]));
}
class Edge implements Comparable<Edge>{
public int a;
public int b;
public int coat;
public Edge(int a,int b,int coat){
this.a = a;
this.b = b;
this.coat = coat;
}
@Override
public int compareTo(Edge o) {
if (coat > o.coat) return 1;
else if (coat == o.coat) return 0;
else return -1;
}
@Override
public String toString() {
return "Edge{" +
"a=" + a +
", b=" + b +
", coat=" + coat +
'}';
}
}
}