Skip to content

Commit 9044a7f

Browse files
committed
kruskal
1 parent da3864e commit 9044a7f

File tree

4 files changed

+119
-4
lines changed

4 files changed

+119
-4
lines changed

.idea/workspace.xml

Lines changed: 5 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Kruskal.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
4+
public class Kruskal {
5+
private WeightedGraph G;
6+
private ArrayList<WeightedEdge> mst;
7+
8+
public Kruskal(WeightedGraph G){
9+
this.G = G;
10+
mst = new ArrayList<WeightedEdge>();
11+
12+
// 需要判断联通
13+
14+
// Kruskal
15+
ArrayList<WeightedEdge> edges = new ArrayList<>();
16+
for(int v = 0;v<G.V();v++){
17+
for(int w : G.adj(v)){
18+
if(v < w){//避免重复
19+
//将边都加入
20+
edges.add(new WeightedEdge(v,w,G.getWeight(v,w)));
21+
}
22+
}
23+
}
24+
25+
// 排序 从小到大
26+
Collections.sort(edges);
27+
28+
// 使用并查集判断是否形成环,若形成环在集合中顶点会有重复
29+
UF uf = new UF(G.V());
30+
for(WeightedEdge edge: edges){
31+
int v = edge.getV();
32+
int w = edge.getW();
33+
if(!uf.isConnected(v, w)){ // v w 是否在一个集合中
34+
mst.add(edge);
35+
uf.unionElements(v, w); // 合并
36+
}
37+
}
38+
39+
}
40+
41+
public ArrayList<WeightedEdge> result(){
42+
return mst;
43+
}
44+
45+
public static void main(String[] args){
46+
47+
WeightedGraph g = new WeightedGraph("g.txt");
48+
Kruskal kruskal = new Kruskal(g);
49+
System.out.println(kruskal.result());
50+
}
51+
}

src/UF.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//并查集
2+
public class UF{
3+
4+
private int[] parent;
5+
6+
public UF(int n){
7+
8+
parent = new int[n];
9+
for(int i = 0 ; i < n ; i ++)
10+
parent[i] = i;
11+
}
12+
13+
public int find(int p){
14+
if( p != parent[p] )
15+
parent[p] = find( parent[p] );
16+
return parent[p];
17+
}
18+
19+
public boolean isConnected(int p , int q){
20+
return find(p) == find(q);
21+
}
22+
23+
public void unionElements(int p, int q){
24+
25+
int pRoot = find(p);
26+
int qRoot = find(q);
27+
28+
if( pRoot == qRoot )
29+
return;
30+
31+
parent[pRoot] = qRoot;
32+
}
33+
}

src/WeightedEdge.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
public class WeightedEdge implements Comparable<WeightedEdge>{
2+
3+
4+
private int v, w, weight;
5+
6+
public WeightedEdge(int v, int w , int weight){
7+
this.v = v;
8+
this.w = w;
9+
this.weight = weight;
10+
11+
12+
}
13+
14+
public int getV(){return v;}
15+
16+
public int getW(){return w;}
17+
18+
@Override
19+
public int compareTo(WeightedEdge another){
20+
return weight - another.weight;
21+
}
22+
23+
@Override
24+
public String toString(){
25+
return String.format("(%d-%d : %d)", v, w,weight);
26+
}
27+
28+
29+
30+
}

0 commit comments

Comments
 (0)