配合上读入类 和 rank 才勉强没超时,呜呜呜
import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Reader {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static String next() throws IOException {// 读取下一个字符串
while (!tokenizer.hasMoreTokens()) {// 返回是否还有分隔符
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();// 返回从当前位置到下一个分隔符的字符串
}
static String nextLine() throws IOException {// 读取下一行字符串
return reader.readLine();
}
static int nextInt() throws IOException {// 读取下一个int型数值
return Integer.parseInt(next());
}
static long nextLong() throws IOException {// 读取下一个long型数值
return Long.parseLong(next());
}
static double nextDouble() throws IOException {// 读取下一个double型数值
return Double.parseDouble(next());
}
}
class edge implements Comparable<edge>{
int a,b,w;
public edge(int a, int b, int w) {
super();
this.a = a;
this.b = b;
this.w = w;
}
@Override
public int compareTo(edge o) {
return this.w-o.w;
}
@Override
public String toString() {
return "edge [a=" + a + ", b=" + b + ", w=" + w + "]";
}
}
public class Main {
public static final int MAXN = 100010;
public static final int MAXM = 200010;
static int m,n;
static edge edges[]=new edge[MAXM];
static int parent[]=new int[MAXN];
static int rank[]= new int [MAXN];
public static void main(String[] args) throws IOException {
CreateGraph();
int ans = Kruskal();
if(ans == -1) System.out.println("impossible");
else System.out.println(ans);
}//main
private static int Kruskal() {
int res=0,cnt=0;
for(int i = 0; i < m; i++) {
int a = edges[i].a;
int b = edges[i].b;
int w = edges[i].w;
int root_a = find_root(a);
int root_b = find_root(b);
if(root_a != root_b) {
cnt++;
res += w;
if(rank[root_a]>rank[root_b])
{
parent[root_b]=root_a;
}
else if (rank[root_a]<rank[root_b]) {
parent[root_a]=root_b;
}else {
parent[root_a]=root_b;
rank[root_b]++;
}
}
}
if(cnt<n-1) return -1;
return res;
}
private static int find_root(int a) {
while(parent[a] != -1) {
a = parent[a];
}
return a;
}
private static void CreateGraph() throws IOException {
n = Reader.nextInt();
m = Reader.nextInt();
for (int i = 0; i < m; i++) {
int a = Reader.nextInt();
int b = Reader.nextInt();
int w = Reader.nextInt();
edges[i] = new edge(a, b, w);
}
Arrays.sort(edges, 0, m);
Arrays.fill(parent, -1);
}
}