具有最少边数的MST

时间:2017-04-25 09:01:39

标签: data-structures minimum-spanning-tree

如何编写逻辑来选择最小生成树 - 如果有多个短路径可用,则边数最少的路径?

这是我的java代码 - 选择最小生成树路径,但不选择边数最少的路径。

  import java.io.BufferedReader;
  import java.io.InputStreamReader;


 public class Kruskal {

   static int path[];
      static int n, m, mincost, i, j;

      public static void main (String args[]) throws Exception {

 InputStreamReader isr;
 isr = new InputStreamReader(System.in);
 BufferedReader in = new BufferedReader(isr);

 // Creating graph of 'n' vertices & 'm' edges
 System.out.print("Enter the number of vertices in the graph: ");
 n = Integer.parseInt(in.readLine());

 System.out.print("Enter the number of edges in the graph: ");
 m = Integer.parseInt(in.readLine());

 path = new int[n+1];

 Edge e[] = new Edge[m];
 Edge t = new Edge();

 for (i=0; i<m; i++) {
   e[i] = new Edge();
   System.out.println("Enter 2 vertices and weight of edge: ");
   System.out.print("First vertex: ");
   e[i].u = Integer.parseInt(in.readLine());
   System.out.print("Second vertex: ");
   e[i].v = Integer.parseInt(in.readLine());
   System.out.print("Weight: ");
   e[i].wt = Integer.parseInt(in.readLine());
 }

 // Sorting the edges in ascending order of weights
 for (i=0; i<=m-1; i++) {
   for (j=0; j<m-i-1; j++) {
     if (e[j].wt > e[j+1].wt) {
       t = e[j];
       e[j] = e[j+1];
       e[j+1] = t;
     }
   }
 }

 // Initializing the path array
 for (i=1; i<=n; i++) {
   path[i] = 0;
 }

 // Counts the number of edges selected in the tree
 i = 0;

 // Counts the number of edges selected or discarded
 j = 0;

 mincost = 0;
 System.out.println();
 while ((i!=n-1) && (j!=m)) {
   System.out.print("Edge ("
   + e[j].u + ", " + e[j].v + ") "
   + "with weight " + e[j].wt + " ");
   if (checkCycle(e[j])) {
     mincost = mincost + e[j].wt;
     i++;
     System.out.println("is selected");
   } else {
     System.out.println("is discarded");
   }
   j++;
 }
 if (i!=n-1) {
   System.out.println("Minimum spanning tree cannot be formed ");
    }

   }

       public static boolean checkCycle(Edge e) {
         int u = e.u, v = e.v;

           while (path[u] > 0)
           u = path[u];

      while (path[v] > 0)
           v = path[v];

      if (u != v) {
      path[u] = v;
        return true;
       }
       return false;
    }

        static class Edge {
         int u, v, wt;
        }
       }

输出:

output

1 个答案:

答案 0 :(得分:1)

Codor链接的简短回答:

  

具有n个节点的无向​​树有多少条边?

     

这是一个非常标准的事实;任何基本文本都会告诉你一个有n个节点的无向​​树必须有n-1个边。

在您的示例中(来自评论),您列出了两条路径但它们最小生成树。最小生成树(MST)或最小权重生成树是连接的,边缘加权的无向图的边缘的子集,其将全部顶点连接在一起。