/// <summary> /// Aplica algoritmo de Prim al grafo para hallar el MSP. /// El Indentificador de los nodes tienen que ser de tipo int /// </summary> /// <param name="graph">Grafo</param> /// <returns>El MSP</returns> public static IEnumerable<IEdge> Run(IGraph graph) { int[] distancia = new int[graph.VertexList.Count]; IVertex[] phi = new IVertex[graph.VertexList.Count]; foreach (IVertex vertex in graph.VertexList) { distancia[(int) vertex.Identifier] = int.MaxValue; phi[(int) vertex.Identifier] = null; } distancia[(int)graph.FirstVertex.Identifier] = 0; var p_Queue = BinomialHeap<int>.Build_Heap(graph.VertexList, x => distancia[(int) x.Identifier]); while (p_Queue.Count > 0) { var current = p_Queue.DeQueue(); foreach (IEdge edge in current.Out) if (p_Queue.Contains(edge.Target) && edge.Cost < distancia[(int) edge.Target.Identifier]) { distancia[(int) edge.Target.Identifier] = (int) edge.Cost; phi[(int) edge.Target.Identifier] = edge.Source; } } for (int i = 0; i < graph.VertexList.Count; i++) { yield return new EdgeResult(graph.VertexList[i], phi[i], distancia[i], false); } }
//<summary> //Aplica algoritmo de Prim al grafo para hallar el MST. //El Indentificador de los nodes tienen que ser de tipo int //</summary> //<param name="graph">Grafo</param> //<returns>El MSP</returns> public static IEnumerable Run(IGraph graph) { int[] distancia = new int[graph.Vertex_Count]; IVertex[] phi = new IVertex[graph.Vertex_Count]; foreach (IVertex vertex in graph.Vertexs) { distancia[vertex.Identifier] = int.MaxValue; phi[vertex.Identifier] = null; } distancia[graph.Vertexs.First().Identifier] = 0; var pQueue = BinomialHeap <IVertex> .Build_Heap(graph.Vertexs, x => distancia[x.Identifier]); while (pQueue.Count > 0) { var current = pQueue.DeQueue(); foreach (IEdge edge in graph.Edg(current)) { if (pQueue.Contains(edge.V_2) && edge.Cost < distancia[edge.V_2.Identifier]) { distancia[edge.V_2.Identifier] = (int)edge.Cost; phi[edge.V_2.Identifier] = edge.V_1; } } } var q = graph.Vertexs.ToArray(); for (int i = 0; i < q.Length; i++) { yield return(new { V_1 = q[i], V_2 = phi[i], Cost = distancia[i] }); } }
private static HNode CreateHeap(IEnumerable <HNode> input) { var heap = BinomialHeap <HNode> .Build_Heap(input, x => x.Count); // O(n) amortized cost while (heap.Count > 1) { var x = heap.DeQueue(); var y = heap.DeQueue(); heap.EnQueue(new HNode { Left = x, Rigth = y, Key = char.Parse(" "), Count = x.Count + y.Count }, x.Count + y.Count); } return(heap.DeQueue()); }