展开全部
求图论算法java实现package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class MinSpanningTree {
class Edge {//内部类定义边的数据结果
int u, v, weight;
}
ArrayList Edges = new ArrayList();
Map nodeFather = new HashMap();
int cnt = 0, nodeCnt = 0;
public MinSpanningTree(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String str;
String[] strArray;
while ((str = br.readLine()) != null) {
strArray = str.split("\\s");
Edges.add(cnt, new Edge());
Edges.get(cnt).u = Integer.parseInt(strArray[0]);
Edges.get(cnt).v = Integer.parseInt(strArray[1]);
Edges.get(cnt).weight = Integer.parseInt(strArray[2]);
if (!nodeFather.containsKey(Edges.get(cnt).u)) {
nodeFather.put(Edges.get(cnt).u, Edges.get(cnt).u);//初始化,father[i]=i;
++nodeCnt;
}
if (!nodeFather.containsKey(Edges.get(cnt).v)) {
nodeFather.put(Edges.get(cnt).v, Edges.get(cnt).v);
++nodeCnt;
}
++cnt;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean union(int u, int v) {//并操作
int a = find(u);
int b = find(v);
if (a != b) {
nodeFather.put(a, b);
return true;
}
return false;
}
public int find(int x) {//查操作
if (x != nodeFather.get(x)) {
nodeFather.put(x, find(nodeFather.get(x)));
}
return nodeFather.get(x);
}
public ArrayList getMinSpanningTree() {
ArrayList result = new ArrayList();
Queue FsQueue = new PriorityQueue(1000,//设置优先队列,使按边e68a843231313335323631343130323136353331333337383836权值从小到大排序
new Comparator() {
public int compare(Edge EdgeOne, Edge EdgeTwo) {
if (EdgeOne.weight > EdgeTwo.weight)
return 1;
else if (EdgeOne.weight
return -1;
else
return 0;
}
});
for (int i = 0; i
FsQueue.add(Edges.get(i));
}
while (!FsQueue.isEmpty()) {//遍历每一条边
Edge Edge = FsQueue.poll();
if (union(Edge.u, Edge.v)) {
result.add(Edge);
} else {
continue;
}
}
return result;
}
public static void main(String[] args) {
MinSpanningTree mstree = new MinSpanningTree("c:/treedata.txt");
ArrayList result = mstree.getMinSpanningTree();
for (int i = 0; i
System.out.println(result.get(i).u + " " + result.get(i).v + " "+ result.get(i).weight);
}
}
}