예제 #1
0
        public void Test_NotEmpty_WhenAdding()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(2);

            pq.Add(18);
            pq.Add(2);

            Assert.False(pq.IsEmpty);
            Assert.Equal(2, pq.Count);
        }
        private KruskalMSTAlgorithm(EdgeWeightedGraph graph)
        {
            // It is more efficient to build a heap by passing array of edges.
            MinPQ <Edge> crossingEdgesByWeight = new MinPQ <Edge>(1);

            this._mst = new Queue <Edge>();

            foreach (Edge edge in graph.GetEdges())
            {
                crossingEdgesByWeight.Add(edge);
            }

            // Greedy algorithm
            UnionFinder uf = new UnionFinder(graph.VerticesCount);

            while (!crossingEdgesByWeight.IsEmpty && this._mst.Count < graph.VerticesCount - 1)
            {
                Edge edge = crossingEdgesByWeight.DeleteMin();

                Int32 sourceVertice = edge.Source;
                Int32 targetVertice = edge.Target;

                if (!uf.IsConnected(sourceVertice, targetVertice))
                {
                    // sourceVertice - targetVertice does not create a cycle.
                    uf.Union(sourceVertice, targetVertice); // Merge sourcerVertice and targetVertice components.

                    this._mst.Enqueue(edge);                // Add edge to minimum spanning tree.

                    this.Weight += edge.Weight;
                }
            }
        }
예제 #3
0
        public void Test_Empty_WhenCleaning()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(1);

            pq.Add(2);
            pq.DeleteMin();

            Assert.True(pq.IsEmpty);
            Assert.Equal(0, pq.Count);
        }
예제 #4
0
        public void Test_Add_Min()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(10);

            for (int i = 1; i < 11; i++)
            {
                pq.Add(i);
            }

            Assert.Equal(1, pq.Min());
        }
예제 #5
0
        public void Test_AddDeleteMin_Order()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(10);

            for (int i = 1; i < 11; i++)
            {
                pq.Add(i);
            }

            for (int i = 1; i < 11; i++)
            {
                Assert.Equal(pq.DeleteMin(), i);
            }
        }