Data structures 边数最少的MST
如果有多条短路径可用,如何编写选择最小生成树-边数最少的路径的逻辑 这是我的java代码-它选择最小生成树路径,但不是边数最少的路径Data structures 边数最少的MST,data-structures,minimum-spanning-tree,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 m
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;
}
}
输出:
来自Codor链接的简短回答: 有n个节点的无向树有多少条边 这是一个非常标准的事实;任何基本文本都会告诉您,具有n个节点的无向树必须正好有n个节点−1.边缘
在注释中的示例中,列出了两条路径,但它们不是最小生成树。最小生成树MST或最小权生成树是连接所有顶点的边加权无向图的边的子集。我不理解这个问题;一个图的每个生成树都有相同数量的边,例如前面讨论过的。在某些情况下,两个或多个mst的权重相等,但边的数量不相等。。A->B1重量,B->C2重量,A->D1重量,D->E1重量,E->C1重量。2个MST路径:A->B->C总重=3 A->D->E->C总重=3;显然,这个问题需要的不是生成树。