6.4 图的应用
6.4.1 最小生成树
1, 最小生成树的基本概念
如果是一个无向连通图,那么它的所有生成树中有一棵边的权值总和最小的生成树,我们称这棵生成树为最小代价生成树,简称最小生成树。
2,普里姆算法(Prim)
假设G=(V,E)为一无向连通图,其中V为网中顶点的集合,E为网中边的集合。设置两个新的集合U和T,其中,U为G的最小生成树的顶点的集合,T为G的最小生成树的边的集合。普里姆算法的思想是:令集合U的初值为U={u1}(假设构造最小生成树时从顶点u1开始),集合T的初值为T={}。从所有的顶点u属于U和顶点v属于V-U的带权边中选出具有最小权值的边(u,v),将顶点v加入集合U中,将边(u,v)加入集合T中。如此不断重复直到U=V时,最小生成树构造完毕。
上面两个无向连通图的最小生成树过程为:
根据邻接链表存储结构实现Prim算法:(邻接链表的实现在前面的博客)
public void Prim()
{
bool[] markers = new bool[NodeNum];
Dictionary<AdjListNode<T>, VexListNode<T>> dic = new Dictionary<AdjListNode<T>, VexListNode<T>>();
for (int j = 0; j < NodeNum; j++)
{
VexListNode<T> vexNode = null;
AdjListNode<T> adjNode = null;
for (int i = 0; i < NodeNum; i++)
{
VexListNode<T> currentVexNode = vexList[i];
AdjListNode<T> currentAdjNode = vexList[i].FirstAdj;
while (currentAdjNode != null)
{
if (markers[currentAdjNode.AdjVexIndex] ^ markers[i])
{
if (adjNode == null || currentAdjNode.Weight < adjNode.Weight)
{
vexNode = currentVexNode;
adjNode = currentAdjNode;
}
}
currentAdjNode = currentAdjNode.Next;
}
}
if (vexNode != null)
{
dic.Add(adjNode, vexNode);
if (markers[adjNode.AdjVexIndex] == false)
markers[adjNode.AdjVexIndex] = true;
else
markers[IsNode(vexNode.Node)] = true;
}
else
{
for (int m = 0; m < NodeNum; m++)
{
if (markers[m] == false)
{
markers[m] = true;
break;
}
}
}
}
foreach (var i in dic.Keys)
{
Console.WriteLine(dic[i].Node.Value.ToString() + " -> " + i.Weight + " -> " + vexList[i.AdjVexIndex].Node.Value.ToString());
}
}
示例图:
调用代码:
GraphAdjList<int> adjList = new GraphAdjList<int>(100);
//Inial graph object
GraphNode<int> node1 = new GraphNode<int>(1);
GraphNode<int> node2 = new GraphNode<int>(2);
GraphNode<int> node3 = new GraphNode<int>(3);
GraphNode<int> node4 = new GraphNode<int>(4);
GraphNode<int> node5 = new GraphNode<int>(5);
GraphNode<int> node6 = new GraphNode<int>(6);
GraphNode<int> node7 = new GraphNode<int>(7);
GraphNode<int> node8 = new GraphNode<int>(8);
adjList.SetNode(node1);
adjList.SetNode(node2);
adjList.SetNode(node3);
adjList.SetNode(node4);
adjList.SetNode(node5);
adjList.SetNode(node6);
adjList.SetNode(node7);
adjList.SetNode(node8);
adjList.SetEdge(0, node2, node1, 2);
adjList.SetEdge(1,node1, node3, 4);
adjList.SetEdge(2,node1, node4, 4);
adjList.SetEdge(3, node1, node5, 3);
adjList.SetEdge(4, node2, node3, 3);
adjList.SetEdge(5, node2, node4, 1);
adjList.SetEdge(6, node2, node5, 2);
adjList.SetEdge(7, node3, node4, 4);
adjList.SetEdge(8, node3, node5, 4);
adjList.SetEdge(9, node5, node4, 2);
adjList.SetEdge(10, node6, node7, 3);
adjList.SetEdge(11, node8, node6, 2);
adjList.SetEdge(12, node7, node8, 3);
adjList.Prim();
adjList.Kruskal();
System.Console.ReadKey();
输出:
2 -> 2 -> 1
2 -> 1 -> 4
2 -> 2 -> 5
2 -> 3 -> 3
8 -> 2 -> 6
6 -> 3 -> 7