这倒题考你最小生成树算法,我参考了算法导论上的Kruskal算法,读者在网上查查 Code/**//*ID: sdjllyh1PROG: agrinetLANG: JAVAcomplete date: 2008/12/28author: LiuYongHui From GuiZhou University Of Chinamore articles: www.cnblogs.com/sdjls*/import java.io.*;import java.util.*;public class agrinet{ private static int n; private static List edges = new ArrayList();//边 private static int cost = 0;//总花费,即题目所求 public static void main(String[] args) throws IOException { init(); run(); output(); System.exit(0); } private static void run() { //根据边的距离排序 Collections.sort(edges); //依次考虑每条边 Iterator it = edges.iterator(); while (it.hasNext()) { edge e = (edge)it.next(); //如果边的两个顶点属于不同的集合 if (e.u.set != e.v.set) { //把此边加入最小生成树 cost += e.w; //合并两个集合 union(e.u.set, e.v.set); } } } private static void union(Set s1, Set s2) { s1.addAll(s2);//把s2集合中的元素加入s1中 //让s2中的每个顶点指向s1集合 Iterator it = s2.iterator(); while (it.hasNext()) { vertex v = (vertex)it.next(); v.set = s1; } } private static void init() throws IOException { BufferedReader f = new BufferedReader(new FileReader("agrinet.in")); n = Integer.parseInt(f.readLine()); vertex[] vertexes = new vertex[n]; for (int i = 0; i < n; i++) { vertexes[i] = new vertex(); } for (int i = 0; i < n; i++) { int j = 0; while (j < n) { StringTokenizer st = new StringTokenizer(f.readLine()); while (st.hasMoreTokens()) { int w = Integer.parseInt(st.nextToken()); if (j > i) { edges.add(new edge(vertexes[i], vertexes[j], w)); } j++; } } } f.close(); } private static void output() throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("agrinet.out"))); out.println(cost); out.close(); }}class edge implements Comparable{ public vertex u, v;//边的两个顶点 public int w;//边的权值,即两个农场之间的距离 public edge(vertex u, vertex v, int w) { this.u = u; this.v = v; this.w = w; } public int compareTo(Object arg0) { edge comObject = (edge)arg0; if (this.w > comObject.w) { return 1; } else if (this.w < comObject.w) { return -1; } else { return 0; } }}class vertex{ public Set set = new HashSet();//包含这个(this)点的集合 public vertex() { this.set.add(this); }} 转载于:https://www.cnblogs.com/SDJL/archive/2008/12/28/1364078.html