public class kruskal {
//并查集
//----------------------------------------------------------------------------------
public void init(int[] ft,int n){
for(int i=1;i<=n;i++)
ft[i] = i;
}
//查找x元素所在的集合
public int find(int[] ft,int key){
int r = key;
while(ft[r]!=r){
r = ft[r];
}
return r;
}
//查找x元素所在的集合,使用路径压缩,递归
public int find1(int[] ft,int key){
if(key!=ft[key]){
ft[key] = find1(ft,ft[key]);
}
return ft[key];
}
//查找x元素所在的集合,使用路径压缩,非递归
public int find2(int[] ft,int key){
int k=0,r=key,j=0;
while(r!=ft[r])
r = ft[r];
k = key;
while(k!=r){
j = ft[k];
ft[k] = r;
k = j;
}
return r;
}
public boolean same(int[] ft,int a,int b){
return find1(ft,a)==find1(ft,b);
}
public int union(int[] ft,int a,int b){
int fa = find1(ft,a);
int fb = find1(ft,b);
if(fa!=fb){
ft[fa] = fb;
}
return fb;
}
//----------------------------------------------------------------------------------
public ArrayList<ANode> sortByEdge(ALGraph AG){
//ALGraph 为图的邻接链表结构
//ANode 为边结构,包含入度端、出度端、权值
ArrayList<ANode> EdgeList = new ArrayList<ANode>();
int n = AG.n;
int[] visited = new int[n+1];
for(int i=1;i<=n;i++){
VNode v = AG.adjList[i];
ANode e = v.firstArc;
visited[i] = 1;
while(e!=null){
if(visited[e.adjVertex]==0){
EdgeList.add(e);
}
e = e.nextArc;
}
}
Collections.sort(EdgeList);
return EdgeList;
}
public void getSpinningTree(ALGraph AG,ArrayList<ANode> EdgeList){
int n = AG.n;
int[] ft = new int[n+1];
ANode e = null;
int start,end;
init(ft,n);
for(int i=0;i<EdgeList.size();i++){
e = EdgeList.get(i);
start = e.sVertex;
end = e.adjVertex;
if(!same(ft,start,end)){ //如果不在同一个集合(连通子图),就相连,即把此边加入集合
union(ft,start,end);
System.out.println(start+"->"+end+"("+e.value+")");
}
}
}
}
java kruskal 算法
最新推荐文章于 2024-07-06 18:27:39 发布