算法分析
时间复杂度 $O(mlogm)$
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static int N = 100010;
static int M = 200010;
static int INF = 0x3f3f3f3f;
static int n;
static int m;
static int[] p = new int[N];
static Edge[] edge = new Edge[M];
static int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
static int kruskal()
{
int res = 0;
int cnt = 0;
Arrays.sort(edge,0,m);
for(int i = 0;i < m;i ++)
{
int a = edge[i].a;
int b = edge[i].b;
int w = edge[i].w;
a = find(a);
b = find(b);
if(a != b)
{
p[a] = b;
res += w;
cnt ++;//计算边数
}
}
if(cnt < n - 1) return INF;
return res;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s1 = br.readLine().split(" ");
n = Integer.parseInt(s1[0]);
m = Integer.parseInt(s1[1]);
for(int i = 1;i <= n;i ++) p[i] = i;
for(int i = 0;i < m;i ++)
{
String[] s2 = br.readLine().split(" ");
int a = Integer.parseInt(s2[0]);
int b = Integer.parseInt(s2[1]);
int w = Integer.parseInt(s2[2]);
edge[i] = new Edge(a,b,w);
}
int t = kruskal();
if(t == INF) System.out.println("impossible");
else System.out.println(t);
}
}
class Edge implements Comparable<Edge>
{
int a,b,w;
Edge(int a,int b,int w)
{
this.a = a;
this.b = b;
this.w = w;
}
@Override
public int compareTo(Edge o) {
// TODO 自动生成的方法存根
return Integer.compare(w, o.w);
}
}
为什么 Arrays.sort(edge) 会出错
为什么要用结构体存储边?
方便
总结的很好
666
算法分析中 “注意” 的第二条应该是 cnt < n - 1 吧 hh
已修改,谢谢大佬提醒